Google Maps - Fixed source and draggable destination in website - maps

I`m using the API to integrate Google Maps in our website. But we did not met the requirement by using them.
I tried using different options. Our requirement is that - the source is set to fixed location(should not be dragged) and the accurate destination is to be entered in the text area and the end user should have an option to point out the exact location(may be near to the location entered in the destination text area).
calculation of distance and the remaining part is working fine for me. Pointing the exact location in the destination also achieved.
Only thing to be worked on is that fixing the source location(End user should not drag/move the source location).
<script type="text/javascript">
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var mapOptions = {
zoom: 4,
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
By using above code, Both the source and destination are draggable.

Google maps marker are not moveable by default, I think, when you set their coordinates on map they stay on the same location.
If still moving you can remove the event listener on the marker

<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
});
var gmarkers = [];
var map = null;
var startLocation = null;
var endLocation = null;
var directionsService = null;
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//google.maps.event.addListener(map, 'click', function () {
// infowindow.close();
//});
directionsService = new google.maps.DirectionsService();
var request = {
origin: document.getElementById("txtSource").value,
destination: document.getElementById("txtDestination").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, RenderCustomDirections);
}
function RenderCustomDirections(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
startLocation = new Object();
endLocation = new Object();
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += route.legs[i].start_address + "<br />" + " to " + "<br />";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
startLocation.marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green", false);
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
var dist_dur = "";
if (steps[j].distance && steps[j].distance.text) dist_dur += " " + steps[j].distance.text;
if (steps[j].duration && steps[j].duration.text) dist_dur += " " + steps[j].duration.text;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
endLocation.marker = createMarker(endLocation.latlng, "end", endLocation.address, "red", true);
}
else alert("Please try again " + status);
}
function createMarker(latlng, label, html, color, draggable) {
//alert("createMarker(" + latlng + "," + label + "," + html + "," + color + ")");
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
draggable: draggable,
map: map,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'dragend', function () {
var request = {
origin: startLocation.marker.getPosition(),
destination: endLocation.marker.getPosition(),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
startLocation.marker.setMap(null);
endLocation.marker.setMap(null);
gmarkers = [];
polyline.setMap(null);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
directionsService.route(request, RenderCustomDirections);
});
return marker;
}
</script>

Related

AngularJS and QUnit: Unknown provider: LocalDataProvider <- LocalData <- FileLogger

Anyone who can help me fix this? I'm such a beginner in unit testing scripts.
Here's my html code.
<html>
<head>
<meta charset = "utf-8">
<title>QUnit and AngularJS</title>
<link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
<script src = "https://code.angularjs.org/1.1.0/angular.js"></script>
<script src = "https://code.angularjs.org/1.1.0/angular-mocks.js"></script>
<script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
<script src = "OfflineStorage/local-storage.service.js"></script>
<script src = "AppLogging/file-logger.service.js"></script>
<script src = "basic.js"></script>
<script src = "qunit.js"></script>
</head>
<body>
<div id = "qunit"></div>
<div id = "qunit-fixture"></div>
</body>
</html>
here's qunit js.
var injector = angular.injector(['ng', 'FileLoggerManager']);
module("File Logger Test", function () {
var svc = injector.get('FileLogger');
});
and here's the one that needed to be tested.
(function() {
'use strict';
angular
.module('FileLoggerManager', [])
.service('FileLogger', Body);
function Body(LocalData, $q, $timeout) {
var service = {
writeLog: writeLog,
SetLogLevel: SetLogLevel,
SetFilePath: SetFilePath,
SetMaxLogSize: SetMaxLogSize,
DeleteLogFiles: DeleteLogFiles,
SendLogsToEmail: SendLogsToEmail
};
// LOG WRITER
var logOb;
var logDirOb;
var logLocation;
var curlogsize = 0;
var logStrings = [];
var loggingStopped = true;
// DEFAULT CURRENT LOG FILE NAME
var logfilename = "MPC";
var appObj = null;
var maxlogsize = 1000000;
var customlogfolder = "sdcard/";
var maxloglevel = 2;
console.log("File Logger initialized.");
// SETTINGS
if (LocalData.loadData('application')) {
appObj = JSON.parse(LocalData.loadData('application'));
// MAX LOGFILE SIZE (BYTES)
maxlogsize = 1000000 * ( appObj.maxLogFileSize ? appObj.maxLogFileSize : 1 );
// LOG SAVE PATH CUSTOM FOLDER NAME
customlogfolder = appObj.logFilePath ? appObj.logFilePath + '/' : 'sdcard/';
// MAX LOG LEVEL (everything below will be logged)
maxloglevel = appObj.logLevel ? appObj.logLevel : 2;
}
// DEVICE READY
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady(){
// WRITE AND GET LOG FILE READY
SetFilePath(customlogfolder);
}
// SET LOG LEVEL
function SetLogLevel(logLevel) {
console.log("File Logger: Set log level to " + logLevel);
maxloglevel = logLevel;
}
// SET FILE PATH
function SetFilePath(filePath) {
while (filePath.indexOf('//') > -1) {
filePath = filePath.replace('//','/');
}
while(filePath[0] == '/') {
filePath = filePath.substring(1);
}
if (filePath[filePath.length-1] != '/') {
filePath = filePath + '/';
}
if (filePath.indexOf('sdcard') == 0) {
filePath = filePath.substring(7);
}
customlogfolder = filePath;
logLocation = cordova.file.externalRootDirectory + customlogfolder;
console.log("File Logger: Log Path = " + customlogfolder);
if (customlogfolder == "") {
initializeLogFile(logLocation);
}
else {
checkIfDirectoryExist(customlogfolder, cordova.file.externalRootDirectory);
}
}
/*
CHECK IF DIRECTORY EXISTS
*/
function checkIfDirectoryExist(filePath, rootDirLoc) {
window.resolveLocalFileSystemURL(filePath, function(dir) {
console.log("File Logger: Path found = " + filePath);
},
function (dir) {
var curFolder = filePath;
var withSubDir = false;
if ((filePath.indexOf('/') > 0) &&
(filePath.indexOf('/') != filePath.length-1)) {
withSubDir = true;
curFolder = filePath.substring(0, filePath.indexOf('/'));
}
window.resolveLocalFileSystemURL(rootDirLoc, function(dir) {
dir.getDirectory(curFolder, { create: true }, function (dirEntry) {
console.log("File Logger: New Directory = " + curFolder );
if(withSubDir == false) {
initializeLogFile(logLocation);
}
},
function(dirEntry) {
console.log("File Logger: Create Dir failed = " + curFolder);
});
},
function(dir){
console.log("File Logger: Root directory not found = " + rootDirLoc);
});
if (withSubDir) {
filePath = filePath.substring(filePath.indexOf('/')+1);
checkIfDirectoryExist(filePath, rootDirLoc + curFolder + '/');
}
});
}
// INITIALIZE AND CREATE LOG FILE
function initializeLogFile(logLocation) {
window.resolveLocalFileSystemURL(logLocation, function(dir) {
logDirOb = dir;
dir.getFile(logfilename + ".txt", { create:true }, function(file) {
logOb = file;
writeToLog();
});
});
}
// SET MAX SIZE
function SetMaxLogSize (maxSize) {
maxlogsize = 1000000 * ( maxSize? maxSize : 1 );
console.log("File Logger: Max File size = " + maxlogsize);
}
// WRITE LOG
function writeToLog() {
if(!logOb){
console.log("File Logger: No log added.");
return;
}
if(logStrings.length == 0) {
return;
}
loggingStopped = false;
logOb.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
logStrings.splice(0,1);
if(logStrings.length == 0) {
loggingStopped = true;
}
else {
loggingStopped = false;
writeToLog();
}
};
var log = logStrings[0];
fileWriter.seek(fileWriter.length);
var blob = new Blob([log], {type:'text/plain'});
fileWriter.write(blob);
}, ReadLogfail);
CheckLogSize();
}
function writeLog(logLevel, str) {
if (maxloglevel == 0) return;
if (maxloglevel>=logLevel && logLevel>0){
var level;
if(logLevel == 4)
level = "DEBUG";
else if(logLevel == 3)
level = "INFO";
else if(logLevel == 2)
level = "WARNING";
else if(logLevel == 1)
level = "ERROR";
var log = "[" + GetLogDate() + "] " + level + " : " + str + "\n";
logStrings.push(log);
if(loggingStopped){
writeToLog();
}
}
}
// CHECK LOG SIZE
function CheckLogSize(){
logOb.file(function(file) {
curlogsize = file.size;
if (parseFloat(curlogsize)>parseFloat(maxlogsize)) {
DeleteLogFiles();
initializeLogFile(logLocation);
}
}, ReadLogfail);
}
function ReadLogfail(e) {
console.log("File Logger: FileSystem Error");
console.dir(e);
}
// GET DATE (SERIAL/NORMAL)
function GetLogDate(){
//var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = new Date();
var dateYear = date.getFullYear();
var dateMonth = LogPad(date.getMonth()+1);
var dateDay = LogPad(date.getDate());
var dateHour = LogPad(date.getHours());
var dateMinute = LogPad(date.getMinutes());
var dateSeconds = LogPad(date.getSeconds());
return dateYear + '.' + dateMonth + '.' + dateDay + ' ' + dateHour + ':' + dateMinute + ':' + dateSeconds;
}
// ADD 0 if number is below 9
function LogPad(n){
return n<10 ? '0'+n : n;
}
// DELETE LOG FILE
function DeleteLogFiles(){
if (!logOb) return 0;
window.resolveLocalFileSystemURL(logLocation, function(dir) {
logDirOb = dir;
dir.getFile(logfilename+".txt", {create:true}, function(file) {
file.remove(function() {
console.log('File logger: File removed = ' + logfilename + ".txt");
});
});
});
}
function SendLogsToEmail() {
cordova.plugins.email.isAvailable( function (isAvailable) {
if(isAvailable) {
cordova.plugins.email.open({
to: '',
subject: 'MSCM MPC Logs',
body: '',
attachments: [logLocation+'MPC.txt',logLocation+'MPC_COMM.txt']
});
} else {
console.log("No email account is setup in this device.");
var confirmPopup = $ionicPopup.alert({
cssClass: 'custom-popup',
template: '<div>{{ "confirm_no_email_setup" | translate }}</div>'
});
};
});
}
return service;
}})();
However while writing QUnit test an error occurs. "Unknown provider: LocalDataProvider <- LocalData <- FileLogger".
Thanks in advance!

how do i display base 64 encoded string as image in ionic app in offline

my code in here
here $scope.student_photo is my variable to get encoded string
first i get it in ajax and stored in local db
$http.post(mData.url+'getStudentDetails/',{student_id : student_id} ).success(function(data){
//$scope.student_pic = data.student_details[0].student_pic;
//$scope.student_photo = data.student_details[0].student_photo;
$scope.myImage=data.student_details[0].student_photo;
//alert($scope.myImage);
// var image_stu = data.student_details[0].student_photo;
// localStorage.setItem("imageData", image_stu);
// document.getElementById("img_stu").src='data:image/png;base64,' + image_stu;
//alert("DONE");
var events = data.student_details
var l = events.length;
//alert(l);
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM dashboard ', [], function(tx, results){
if (results.rows.length == 0)
{
tx.executeSql("INSERT INTO dashboard(dashboard_id, stu_name,clas,sec,student_image) VALUES(?,?,?,?,?)", [ student_id,data.student_details[0].student_name, data.student_details[0].class_name, data.student_details[0].section_name,data.student_details[0].student_photo], function(tx, res) {
$scope.dashboardDetails();
//alert('INSERTED');
}, function(e) {
//alert('ERROR: ' + e.message);
});
}
});
});
});
$scope.showScreen = function(screen) {
$state.go('app.'+screen);
}
$scope.printDashboard = function()
{
//alert('ss');
db.transaction(function (tx) {
// tx.executeSql('SELECT * FROM dashboard', [], function (tx, dtresult) {
//alert("dtresult.rows.length" + dtresult.rows.length);
// console.log("dtresult.rows.length" + dtresult.rows.length);
// $scope.totalrecords = dtresult.rows.length;
// });
tx.executeSql('SELECT * FROM dashboard', [], function (tx, dresult) {
console.log("dresult.rows.length" + dresult.rows.length);
dataset = dresult.rows;
console.log(dresult.rows);
for (var i = 0, item = null; i < dresult.rows.length; i++) {
item = dataset.item(i);
$scope.dashboarditems.push({stu_name: item['stu_name'],stu_class: item['clas'],stu_sec: item['Sec'],stu_img: item['student_image']});
//$scope.items.push({id: item['notice_title'], notice:item['notice'], event_date: item['event_date']});
console.log($scope.dashboarditems[0]);
}
$state.go('app.dashboard');
});
});
}
$scope.dashboardDetails = function()
{
var citems = [];
syncWithServer(function(syncSuccess){
$scope.printDashboard();
}, false);
}
Question:
How to display my base64 string to image formate.
If your base64 string is present inside the $scope.student_photo
try the following img tag to display the image in view
<img ng-src="{{'data:image/png;base64,'+student_photo}}">

Can't $update or $set ~ "undefined is not a function" ~ AngularFire

What I'm trying to do:
Update the status to "TAKEN" when the chat is closed.
Issue:
Can't get $scope.currentChat.$set() or $scope.currentChat.$update() to work when trying to update the status. (See the $scope.close() function.)
What I've tried:
Various methods including $set, $update; I don't know. A lot of things. Been researching this for several hours, and can't find a solution that works.
NOTES:
$scope.currentChat.$set({status:"TAKEN"}); Doesn't work.
$scope.currentChat.$getRecord('status'); Works. Returns:
Object {$value: "OPEN", $id: "status", $priority: null}
So what exactly is going on here? Why can't I seem to set the status to TAKEN?
The issue is currently in the $scope.close() function, when trying to update the status:
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
Here's my code:
bloop.controller('HomeCtrl', ['$scope', '$firebase', function($scope, $firebase) {
console.log("HomeController!");
var url = 'https://**********.firebaseio.com/tickets/';
var ref = new Firebase(url);
// $SCOPE.CREATETICKET
// - This function makes a connection to Firebase and creates the ticket.
$scope.createTicket = function() {
$scope.tickets = $firebase(ref).$asArray();
$scope.tickets.$add($scope.ticketObject).then(function(r) {
var id = r.name();
$scope.currentFBID = id;
$scope.syncTickets();
console.log("===========================");
console.log("CREATED TICKET: " + $scope.currentFBID);
console.log("URL: " + url + $scope.currentFBID);
console.log("===========================");
});
}
// $SCOPE.SYNCTICKETS
// - This function makes a connection to Firebase and syncs the ticket with the $scope to easily update the tickets.
$scope.syncTickets = function() {
var ticketRefURL = new Firebase(url + $scope.currentFBID);
$scope.currentChat = $firebase(ticketRefURL).$asArray();
$scope.currentChat.$save($scope.ticketObject);
var archiveRefURL = new Firebase(url + $scope.currentFBID + "/archive");
$scope.currentChat.archive = $firebase(archiveRefURL).$asArray();
console.log("===========================");
console.log("SAVED TICKET: " + $scope.currentFBID);
console.log("URL: " + ticketRefURL);
console.log("ARCHIVE URL: " + archiveRefURL);
console.log("===========================");
}
// $SCOPE.POST
// - This function pushes whatever is typed into the chat into the chat archive.
// - $scope.ticketObject.archive (is an array of objects)
$scope.post = function(name) {
// Push to ticketObject.archive array...
$scope.ticketObject.archive.push({
"name" : name,
"text" : $scope.chatText
});
// Logging the array to make sure it exists...
console.log("===========================");
console.log("CHAT ARCHIVE:");
console.log($scope.ticketObject.archive);
console.log("===========================");
$scope.currentChat.archive.$add({
"name" : name,
"text" : $scope.chatText
});
// This resets the text area so it's empty...
$scope.chatText = "";
} // WORKS
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
// $SCOPE.TOGGLE
// - This function toggles the chat to be either open or closed.
$scope.toggle = function() {
if($scope.toggleState === false) {
$scope.toggleState = true;
$scope.checkTicket();
} else if($scope.toggleState === true) {
$scope.toggleState = false;
}
}
// $SCOPE.CHECKTICKET
// - This function checks to see if there's an existing ticket.
// - If there's not an existing ticket, it creates one.
$scope.checkTicket = function() {
if($scope.ticket === false) {
// Generate New Ticket Data
$scope.ticketObject = newTicket();
// Create the Ticket
$scope.createTicket();
// Ticket now exists.
$scope.ticket = true;
}
}
function newTicket() {
var ticketID = generateTicketID();
var newTicket = {
id: ticketID,
status: "OPEN",
name: "N/A",
email: "N/A",
date: generateDate(),
opID: "Unassigned",
opName: "Unassigned",
archive: [],
notes: []
}
return newTicket;
}
function generateTicketID() {
var chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var result = '';
for(var i=12; i>0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
function generateDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd;
}
if(mm < 10) {
dd = '0' + mm;
}
var date = mm + "/" + dd + "/" + yyyy;
return date;
}
}]);
$update and $set are part of the $firebase API. You are attempting to call them on the synchronized array returned by $asArray(), which is a $FirebaseArray instance. That has its own API, which includes neither update nor set.

Google maps need to show list of addresses -setimout slow and OVER_QUERY_LIMIT issue

Hi everyone i have a bout 500 addresses or so to be listed in Google maps , each address being grabbed from a filemaker database than grouped under a category person(employee name in the map) i'm using a function to geocode and i'm calling it every 10th time with a 10 sec
setimout, the problem is:
1- the page is very very slow with settimeout 10sec when you have to show 500 addresses( addresses can change any second never fixed addresses) is there a better way?
2- even with settimout set to call every 10 seconds, i still get sporadically OVER_QUERY_LIMIT , why does that happen, 10 seconds is along time.
here is the code:
<pre><script type="text/javascript">
var mapOptions = {
//center:myLatLng,
//zoom:15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
//var contentString='<div id="google_info_window">I;m Here</div>';
//var infowindow = new google.maps.InfoWindow();
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var addresses = new Array();
var gmarkers = [];
addresses = <?php echo json_encode($project_info); ?>;
console.log("Addresses: <pre>"+JSON.stringify(addresses));
<?php //foreach($project_info as $i => $val){?>
//addresses.push('<?php //echo $val; ?>');
<?php //}?>
var bounds = new google.maps.LatLngBounds();
i=1;
mySleepFunction();
function mySleepFunction()
{
var geocoder = new google.maps.Geocoder();
//var myLatLng = new google.maps.LatLng(30,-50);
//var contentString='<div id="google_info_window">I;m Here</div>';
//for(var i = 0; i<Object.keys(addresses).length; i++)
var show_message= document.getElementById('map_message');
show_message.style.display="block";
show_message.innerHTML ="<div>Loading Please Wait...</div>";
for (; i < 200; i++) {
if(i %10 == 0) {
setTimeout(geocoder.geocode({'address': addresses[i-1]['Address']}, makeCallback(i)),2000);
i++;
setTimeout("mySleepFunction()",9000);
break;
}
geocoder.geocode({'address': addresses[i-1]['Address']}, makeCallback(i));
if (i==199){
show_message.style.display = 'none';
}
}//For statement
function makeCallback(addressIndex) {
var i = addressIndex-1;
var geocodeCallBack = function(results, status) {
if (status != google.maps.GeocoderStatus.OK) {
console.log("Geocode was not successful for the following reason: " + status);
} else {
var p = results[0].geometry.location;
var address_formated = results[0].formatted_address;
var appraiser = addresses[i]['Staff'];
//var latlng = new google.maps.LatLng(p.lat,p.lng);
map.setCenter(p);
createMarker(map,address_formated,p,appraiser);
// sets the center point to be the p
//map.setZoom(10); // sets the zoom level
//bounds.extend(latlng);
// main.setMap(map, point, titles[i], bounds);
show(appraiser);
}
}
return geocodeCallBack;
}// fUNCTION MAKECALLBAC
}
//map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.fitBounds(bounds);
// map.panToBounds(bounds);
function createMarker(map,add,p,appraiser) {
var str = add;
var numb=str.indexOf(',');
//alert("position of:"+numb);
str = str.substr(0, numb+1) +"<br/>"+ str.substr(numb+1);
var contentString = '<div id="google_info_window" style="min-height:40px;height:auto;width:auto;"><strong>'+appraiser+'</strong><p style="margin:1px;padding:5px 1px 2px 1px">'+str+'</p></div>';
//var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
title:appraiser,
position: p
});
marker.mycategory = appraiser;
gmarkers.push(marker);
//Open the infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
infowindow.setContent(contentString);
});
marker.setMap(map,bounds);
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(appraiser) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == appraiser) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
var appraiser_id = appraiser.replace(/\s/g,"");
var apraiser_checkbox_id = appraiser_id+"_Checkbox";
document.getElementById(appraiser_id+"_Checkbox").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(appraiser) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == appraiser) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
var appraiser_id = appraiser.replace(/\s/g,"");
document.getElementById(appraiser_id+"_Checkbox").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}
function boxclick(box,appraiser) {
if (box.checked) {
show(appraiser);
} else {
hide(appraiser);
}
// == rebuild the side bar
}
// google.maps.event.addDomListener(window, 'load', initialize);
</script></pre>

Adding XML attributes to GMap3 infoBubbles

Although I got this working in Gmapv2..version three is proving to be a little trickier.
I wanted to add the other attributes into the infobubble from the XML file, but whereever I try and add them, it breaks the on-click marker?
<script type="text/javascript">
var infowindow;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(54.046575, -2.8007399);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("http://www.xxxxxx.com/xxxxx.com/server/venue_output.php", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var event_name = markers[i].getAttribute("event_title");
var event_start = markers[i].getAttribute("event_start");
var event_link = markers[i].getAttribute("event_link");
var marker = createMarker(markers[i].getAttribute("event_name"),latlng);
}
});
}
function createMarker(name, latlng) {
var marker = new google.maps.Marker({position: latlng, map: map, bounce:true, icon : new google.maps.MarkerImage('http://www.gigizmo.com/gigizmo.com/app/images/marker.png')});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
infowindow.open(map, marker);
});
return marker;
}
</script>
How do I add my javascript values such as event_link to this marker window?
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
You may try this code snippet, provided at : this example
function createMarker(..){
eval(" infowindow"+time+" = new google.maps.InfoWindow({ content: pt.latLng.toString() });");
eval(" marker"+time+" = new google.maps.Marker({ position: pt.latLng, map: map });");
eval(" google.maps.event.addListener(marker"+time+", \"click\", function() { infowindow"+time+".open(map, marker"+time+"); });");
time++;
//rest of your code
}
And also, speaking of my previous experiences:
be sure that your XML file does not include linebreaks.
Especially as the value you set to "name" variable.

Resources