First, I'm using the library from : http://www.pittss.lv/jquery/gomap/examples/marker.php,
and I'm using a webservice to get data.
I would like to locate these informations on the map, but i can't know before, how many elements I will have to create.
To get data I have this code :
$('#default-search').submit(function () {
var gomap_marker = [];
var search_where = $('#search-where').val();
if ($('#search-where').val() == "")
search_where = "-1";
$.ajax({
url: "http://my_url.com/",
contentType: "json",
data: {
city: search_where
},
success: function (data) {
//List received data
$.each(data, function (index, item) {
//create an array with data
gomap_marker.push({
id: item.Id,
address: item.Street + ', ' + item.ZipCode + ' ' + item.City,
icon: 'images/marker.png',
group: 'toshow',
html: '' + item.Street + ', ' + item.ZipCode + ' ' + item.City + ''
});
}); // END - $.ajax success each
// valid test
for (var i = 0; i < gomap_marker.length; i++) {
alert('1 - ' + gomap_marker[i].id + gomap_marker[i].address + gomap_marker[i].html);
}
// reset the map for each request
$("#map").removeData();
alert('Test');
// map init + markers
jQuery('#map').goMap({
maptype: 'ROADMAP',
zoom: 13,
scaleControl: true,
scrollwheel: false,
markers: gomap_marker
});
}, // END - $.ajax success
error: function () { alert("simple request goes wrong"); }
}); // END - $.ajax
return false;
}); // END - default-search
Only the first row of my array create a marker on the map. I don't understand how to set the others.
I would like to use $.goMap.createMarker instead of creating an array and reset the map, but I had the same problem : only the first row created a marker on the map.
Regards,
emm First create an array of lat,long
var data = new Array();
data[0] = new Array();
data[0][0] = 'FOOD'; //name
data[0][1] = '23,23';//coordinates(lat,lng)
function HTMLMarker( place ) {
this.name = place[0];
var latLngStrings = place[1].split(',');
var lat = +latLngStrings[0];
var lng = +latLngStrings[1];
this.pos = new google.maps.LatLng( lat, lng );
}
HTMLMarker.prototype = new google.maps.OverlayView();
HTMLMarker.prototype.onRemove = function () {};
HTMLMarker.prototype.onAdd = function () {
var div = this.div = document.createElement('DIV');
div.className = "htmlMarker";
div.innerHTML = ''+this.name+'';
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
};
HTMLMarker.prototype.draw = function () {
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var panes = this.getPanes();
this.div.style.left = position.x - 30 + 'px';
this.div.style.top = position.y - 48 + 'px';
};
function initialize() {
var myLatLng = new google.maps.LatLng(23,23);
var mapOptions = {
zoom: 15,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmap = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
for (var i = 0; i < data.length; i++) {
addMarker( data[i] );
}
function addMarker( place ) {
var htmlMarker = new HTMLMarker( place );
htmlMarker.setMap(gmap);
}
}
google.maps.event.addDomListener( window, 'load', initialize );
This should work!!
I am creating the array with php:
<script>
<?php $i = 0;
foreach($places as $place) {
$pins = $place['pins']; //coordinates
$name = $place['name'];
echo "data[$i] = new Array();\n";
echo "data[$i][0] = '" .$name. "';\n";
echo "data[$i][1] = '" .$pins. "';\n";
$i++;
} ?>
</script>
ALSO In css add this
.htmlMarker {
position: absolute;
}
Related
i have an phone gap application , and i was working with sub function in other project in phonegap that has java script index file , now i want to integrate the sub index file to my original project , and i know i cant have two indexes file because phonegap app has onsucees , and deviceReady function
i want to convert this code to a regular java script file
$("#tourButton").click(function(){
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
// app.receivedEvent('deviceready');
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onError);
},
onSuccess: function(position){
//My coordinates: Latitude: 21.371479, Longitude: 39.794234
//var longitude = position.coords.longitude;
//var latitude = position.coords.latitude;
var longitude = 39.794234;
var latitude = 21.371479;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title: 'my location'
});
//document.getElementById("jjj").innerHTML=longitude + ", " + latitude;
var hours = $("input:text").val();
var radioValue = $("input[name='transport']:checked").val();
var distanceInKM;
var serviceURL ;
var dataArray = [];
var query ;
var matches = hours.match(/^\d{1,2}(?:\.\d{1,2})?$|^\.\d{1,2}$/);
if (hours!="" && !matches){
alert( " القيمة " + hours + " غير صحيحة .. الرجال ادخال قيمة اخرى (مثال 4 أو 4.5) " );
}
else if (!hours.match(/\S/)) {
alert(" الرجاء تحديد ساعات الفراغ ");
}
else if ($("input[type=radio]:checked").length <= 0) {
alert("الرجاء اختيار وسيلة المواصلات المفضلة");
}
else if (hours>0 && radioValue == "DRIVING") { //DRIVING is selected
distanceInKM = drivingDistanceCal(hours);
//document.getElementById("mmm").innerHTML = drivingDistanceCal(hours);
serviceURL = "http://192.168.8.100/maleem/distanceTran.php";
query = { user: distanceInKM, lat: latitude, lng: longitude };
}
else if (hours>0 && radioValue == "WALKING") { //WALKING is selected
distanceInKM = walkingCalDistanceCal(hours);
//document.getElementById("mmm").innerHTML = walkingCalDistanceCal(hours);
serviceURL = "http://192.168.8.100/maleem/distanceTran.php";
query = { user: distanceInKM, lat: latitude, lng: longitude };
}
else{
alert(" الرجاء تحديد ساعات الفراغ بالإضافة إلى وسيلة المواصلات ");
}
function drivingDistanceCal(hours){
distanceInKM = (45 * hours)/3;
return distanceInKM;
//alert(distanceInKM);
}
function walkingCalDistanceCal(hours){
distanceInKM = (4.82803 * hours)/3;
return distanceInKM;
//alert(distanceInKM);
}
$.getJSON( serviceURL,query)
.done(function( data ) {
if(data.items == "no data"){
alert("عذراً لا توجد نتائج");
}
else{
$.each( data.items, function( i, item ) {
dataArray.push([item.L_ID , item.Lat , item.Lon , item.Description ,item.Image , item.Title, item.Type_ID, ]);
});
//document.getElementById("mmm").innerHTML = dataArray.length;
//document.getElementById("result1").innerHTML = dataArray[1][1] + ", " + dataArray[1][2];
document.getElementById("back").style.display = 'block';
var button;
var content = document.getElementById("content");
for(var i = 0 ; i < dataArray.length; i++){
var table = document.getElementById("table");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = dataArray[i][5];
//cell2.innerHTML = dataArray[i][0];
var btn = document.createElement("BUTTON");
var t = document.createTextNode("اختر");
btn.appendChild(t);
btn.setAttribute("id",dataArray[i][0]);
cell2.appendChild(btn);
var tempArray = dataArray[i];
btn.onclick = (function(tempArray) {
return function() {
corefunction(tempArray);
};
}(dataArray[i]));
}
function corefunction(tempArray){
//alert(tempArray[5]);
document.getElementById("back").style.display = 'none';
var distLat;
var distLng;
// start the countdown functionality
// calculating the time in seconds
var twentyFourHours = hours * 60 * 60;
//var twentyFourHours = 1 * 60;
var display = $('#remainingTime');
Timer(twentyFourHours, display);
var begin;
// dislay the timer
function Timer(duration, display){
var timer = duration, hours, minutes, seconds;
begin = setInterval(function () {
hours = parseInt((timer /3600)%24, 10)
minutes = parseInt((timer / 60)%60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(hours +":"+minutes + ":" + seconds);
if(timer==600){
alert(" باقي لك١٠ دقايق " );
}
if(timer > 0){
--timer;
}
else if(timer==000){
alert(" انتهت الرحلة وإن شاء الله تكون استفدت ");
window.clearInterval(begin);
}
}, 1000);
var map;
var stop = document.getElementById("stop");
//create buttons for events
var stopbtn = document.createElement("BUTTON");
var t = document.createTextNode("أوقف الرحلة");
stopbtn.appendChild(t);
stopbtn.setAttribute("id","stop");
stop.appendChild(stopbtn);
//display path
distLat = tempArray[1];
distLng = tempArray[2];
var latLong = new google.maps.LatLng(distLat, distLng);
initMap();
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 21.389082, lng: 39.857912},
//disableDefaultUI: true
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: {lat:latitude,lng:longitude},
destination: latLong,
travelMode: radioValue
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
//autoUpdate();
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
//tracking part
var marker2 = null;
var auto;
function autoUpdate() {
var newLat = position.coords.latitude;
var newLng = position.coords.longitude;
var newlatLong = new google.maps.LatLng(newLat,newLng);
navigator.geolocation.getCurrentPosition(function(position) {
//var newPoint = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var latLong2 = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if (marker2) {
// Marker already created - Move it
marker2.setPosition(latLong2);
}
else {
// Marker does not exist - Create it
marker2 = new google.maps.Marker({
position:newlatLong,
map: map
});
}
// Center the map on the new position
map.setCenter(latLong2);
});
auto = setTimeout(autoUpdate, 1000);
//Latitude: 21.419833 | Longitude: 39.832421
var distance = haversine(21.419833,39.832421,tempArray[1],tempArray[2]);
//var distance = haversine(newLat,newLng,tempArray[1],tempArray[2]);
function haversine(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
if (distance<=1){
alert("وصلت/اقتربت من وجهتك");
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 21.389082, lng: 39.857912},
//disableDefaultUI: true
});
var marker = new google.maps.Marker({
position: latLong,
map: map
});
window.clearInterval(begin);
window.clearTimeout(auto);
stop.removeChild(stopbtn);
}
}
autoUpdate();
//buttons events
$("#stop").click(function(){
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 21.389082, lng: 39.857912},
//disableDefaultUI: true
});
var marker = new google.maps.Marker({
position: latLong,
map: map
});
window.clearInterval(begin);
window.clearTimeout(auto);
stop.removeChild(stopbtn);
});
}//end of timer function
}//end of function showRout()
}//end of else
}); //end of getJSON()
}, //end of success state
onError: function(error){
alert("the code is " + error.code + ". \n" + "message: " + error.message);
},//end of error state
};//end of app variable
app.initialize();
}); //end of the whole function
I am using google maps and i have working code to display markers on a map. I now want to put this code inside of a function view_maps() and activate this function on click. So far i get the errors Maximum call stack size exceeded and getAddress is not a function. This works but when the code inside of view_maps() function i get these errors.
function view_maps() {
function marker_map() {
var url = "http://example.co.uk/deliveries/map/get_region_orders";
var region = $("ul#regions").children("li[data-active='1']").attr("class");
var data = {
region: region
};
var obj = {};
var locations = [];
var details_array = [];
$.ajax({
type: "POST",
url: "http://example.co.uk/deliveries/map/get_region_orders",
data: data,
async: false,
success: function(response) {
var result = $.parseJSON(response);
jQuery.each(result, function(i) {
var order_id = result[i].order_id;
var customer_name = result[i].customer_name;
var address_1 = result[i].address_1;
var address_2 = result[i].address_2;
var post_code = result[i].post_code;
var address = post_code;
var details = "<b>Order Number: " + order_id + "</b><br>" + address_1 + "<br>" + address_2 + "<br>" + post_code;
details_array.push(details);
locations.push(address);
});
}
});
obj['address'] = locations;
obj['details'] = details_array;
return (obj);
}
// delay between geocode requests - at the time of writing, 100 miliseconds seems to work well
var delay = 70;
// ====== Create map objects ======
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(53.381021, -2.608138);
var mapOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geo = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("marker-map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
// ====== Geocoding ======
function getAddress(search, count, next) {
geo.geocode({
address: search
}, function(results, status) {
// If that was successful
if (status == google.maps.GeocoderStatus.OK) {
// Lets assume that the first marker is the one we want
var p = results[0].geometry.location;
var lat = p.lat();
var lng = p.lng();
// Output the data
var msg = 'address="' + search + '" lat=' + lat + ' lng=' + lng + '(delay=' + delay + 'ms)<br>';
document.getElementById("messages").innerHTML += msg;
// Create a marker
createMarker(search, count, lat, lng);
}
// ====== Decode the error status ======
else {
// === if we were sending the requests to fast, try this one again and increase the delay
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
var reason = "Code " + status;
var msg = 'address="' + search + '" error=' + reason + '(delay=' + delay + 'ms)<br>';
//document.getElementById("messages").innerHTML += msg;
}
}
next();
});
}
// ======= Function to create a marker
function createMarker(add, count, lat, lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details_array[count]);
//infowindow.setContent(contentString);
infowindow.open(map, marker);
});
bounds.extend(marker.position);
}
// ======= An array of locations that we want to Geocode ========
//console.log(marker_map());
var locations = marker_map();
var addresses = locations.address;
var details_array = locations.details;
// ======= Global variable to remind us what to do next
var nextAddress = 0;
// ======= Function to call the next Geocode operation when the reply comes back
function theNext() {
if (nextAddress < addresses.length) {
setTimeout('getAddress("' + addresses[nextAddress] + '","' + nextAddress + '",theNext)', delay);
nextAddress++;
} else {
// We're done. Show map bounds
map.fitBounds(bounds);
}
}
// ======= Call that function for the first time =======
theNext();
}
How do i solve? I think this is to do with scope of functions because getAddress is clearly a function.
you have to change your theNext function with this one.
function theNext() {
if (nextAddress < addresses.length) {
setTimeout(getAddress(addresses[nextAddress],nextAddress,theNext), delay);
nextAddress++;
} else {
// We're done. Show map bounds
map.fitBounds(bounds);
}
}
see change in setTimeout, I am Calling function not passing string (which will evaluate later and search in global scope)
I also create a demo for proof of concept. Enjoy :)
I am working on a google maps project where I am populating the google maps with markers being read from a database (drawMarkers function). Along with that the google maps finds your current location and keeps refreshing it every couple of seconds to keep track of you on the map. My issue is that have a var closest which is also a function i am using the too find the closest marker then create directions to current locations from there. I did not know how to actually find the closest marker so i borrowed the code from another question from stack overflow and tried to adapt it to this project. I need help to get my closest function to find the closest marker and then to make it the destination in the direction service
$ionicSideMenuDelegate.canDragContent(false);
$scope.getTourMarkers = function () {
tourmarkers.getTourMarkers().success(function (data) {
$scope.tourmarkers = data;
console.log($scope.tourmarkers);
drawMarkers();
});
};
var drawMarkers = function () {
var markers;
var content;
var infoWindow;
for (var i = 0; i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
content: content
});
var point = new google.maps.LatLng($scope.tourmarkers[i].lat, $scope.tourmarkers[i].lon);
markers = new google.maps.Marker({
label: "S",
animation: google.maps.Animation.DROP,
position: point,
map: map,
info: content
});
//SCOPE: 'this' refers to the current 'markers' object, we pass in the info and marker
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
};
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var NAPA_HALL_LAT_LNG = new google.maps.LatLng(38.553801, -121.4212745); // just created this marker for testing purposes
var mapOptions = {
center: myLatlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'SAC STATE'
});
var dest = new google.maps.Marker({
position: NAPA_HALL_LAT_LNG,
map: map,
title: 'NAPA HALL'
});
///////////////////Directions Display//////////////////////
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//////////////////////////////////////////////////////////////////////////////////////////
//Goal of this function is to find closest marker to current location
//then to create directions to that marker.
//should be refreshed everytime in the onSuccess function
var closest = function (directionsService, directionsDisplay, marker, dest) {
var event;
function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var R = 6371; // radius of earth in km
var distances = [];
var shortest = -1;
for( i=0;i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
var mlat = $scope.tourmarkers[i].position.lat();
var mlng = $scope.tourmarkers[i].position.lng();
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( shortest == -1 || d < distances[shortest] ) {
shortest = i;
}
}
alert(map.markers[shortest].title);
}
/////**directions feature should have the closest marker be the desitination//
directionsService.route({
origin: marker.position,
destination: dest.position, // i think the marker that should in here is shortest.
travelMode: google.maps.TravelMode.WALKING
}, function(response,status) {
if(status==google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
//////////////////////////////////////////////////////////////////////////////////////////
var onSuccess = function (position) {
marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
directionsDisplay.setMap(map);
dest.setPosition(new google.maps.LatLng(38.553801, -121.4212745));
//dest.setPosition((closest(marker, $scope.tourmarkers)).position); // if you can get this line to work without commenting it out then you're set
closest(directionsService,directionsDisplay, marker,dest);
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
Everything in this project is working properly except that closest function. but even then i have already tested the directionservice and even that is working too. I just need help making the destination in the direction service to be the closest marker to current location.
i think this code is helpful for you i used this code in my project such that your requirement same as my requirement
in the below function 'data' means list of lat lng's from server
function initialize(data) {
size = 0;
counts = 0;
stops = data;
size = stops.length;
if (stops.length > 0) {
var map = new window.google.maps.Map(document
.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer(
{
suppressMarkers : true,
polylineOptions : {
strokeColor : "black"
}
});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map,stops);
/* if (stops.length > 1) */
window.tour.calcRoute(stops,directionsService,
directionsDisplay,size);
}
}
function Tour_startUp(stops) {
var stops=stops;
var counts=0;
if (!window.tour) window.tour = {
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom:10,
center: new window.google.maps.LatLng(17.379818, 78.478542), // default to Hyderabad
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map,stops) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (stops,directionsService, directionsDisplay,size) {
size=size;
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
var tempp=0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
tempp++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].latitude, stops[j].longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
//delay(600);
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
//alert("count test");
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
var totdist=0;
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
var markerletter2= "B".charCodeAt(0)
markerletter += i;
markerletter2 += i;
markerletter = String.fromCharCode(markerletter);
markerletter2 = String.fromCharCode(markerletter2);
createMarker(directionsDisplay.getMap(),legs[i].start_location,legs[i].start_address,markerletter,size);//To display location address on the marker
var routeSegment = i + 1;
var point=+routeSegment+1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += '<b>Point '+ routeSegment +' :</b>'+ ' ' +legs[i].start_address + ' <br> ';
summaryPanel.innerHTML += '<b>Point '+ point +' :</b>'+ ' '+legs[i].end_address + '<br>';
summaryPanel.innerHTML += '<b>Distance Covered '+' :</b>'+legs[i].distance.text + '<br><br>';
var test=legs[i].distance.text.split(' ');
var one=parseFloat(test[0]);
if(test[1]=="m"){
var one=parseFloat(test[0]/1000);
}
totdist=parseFloat(totdist)+parseFloat(one);
}
summaryPanel.innerHTML += '<b> Total Distance :'+totdist + 'km'+ '</b><br><br>';
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,legs[legs.length-1].end_address,markerletter,size);
}
}
});
})(k);
function delay(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
}
}//calculate route end
};
}
//to show information on clicking marker
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr,size) {
counts++;
if(counts==size){
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/blue.png";
counts = 0;
}else{
if (iconStr=="undefined") {
iconStr = "red";
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
else{
var markerimageLoc="http://www.google.com/mapfiles/marker"+ iconStr +".png";
// var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
}
icons[iconStr] = new google.maps.MarkerImage(markerimageLoc,
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(25, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, character,size) {
var markerletter = character;
var size=size;
if (/[^a-zA-Z]/.test(character)) {
var markerletter = "undefined";
}
var contentString = '<b>' + label + '</b><br>';
var marker = new google.maps.Marker({
position : latlng,
map : map,
shadow : iconShadow,
icon : getMarkerImage(markerletter,size),
shape : iconShape,
title : label,
zIndex : Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
return marker;
}
Having trouble adding links that will center and open an info window on my google map. The markers and their info windows work fine within the map itself.
The real problem is constructing an object that my onclick function can reference properly. My object oriented Javascript knowledge is shaky and I'm just not seeing the solution.
The map is loaded via a function that's called on page load and I have a seperate function that's called on click of an href within the page.
Code is below.
function addMap(addressesJSON, id){
var addresses = eval('(' + addressesJSON + ')');
var cenLat = 41.677389;
var cenLng = -72.384294;
var latLow = 41.4;
var lngLow = -72.8;
var latHigh = 41.8;
var lngHigh = -71.9;
if (addresses.length){
for (var i in addresses){
addresses[i].lat = parseFloat(addresses[i].lat);
addresses[i].lng = parseFloat(addresses[i].lng);
if (i == 0){
latLow = addresses[i].lat;
latHigh = addresses[i].lat;
lngLow = addresses[i].lng;
lngHigh = addresses[i].lng;
} else {
if (addresses[i].lat < latLow){
latLow = addresses[i].lat;
}
if (addresses[i].lat > latHigh){
latHigh = addresses[i].lat;
}
if (addresses[i].lng < lngLow){
lngLow = addresses[i].lng;
}
if (addresses[i].lng > lngHigh){
lngHigh = addresses[i].lng;
}
}
address = "<span style=\"color: #0000ff\">" + addresses[i].name + "</span><br/>" + addresses[i].address + "<br/>Directions: To - From";
addresses[i].address = address;
}
cenLat = (latLow + latHigh) / 2;
cenLng = (lngLow + lngHigh) / 2;
}
var mapOptions = {
center: new google.maps.LatLng(cenLat, cenLng),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Display a map on the page
var map = new google.maps.Map(document.getElementById(id), mapOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in addresses){
var letter = addresses[i].letter;
var data = addresses[i].address;
var myLatlng = new google.maps.LatLng(addresses[i].lat, addresses[i].lng);
var latlng = new google.maps.LatLng(addresses[i].lat, addresses[i].lng);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: addresses[i].name,
icon: "http://maps.google.com/mapfiles/marker" + letter + ".png"
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function () {
// Center on marker
map.setCenter(marker.getPosition());
// Set the data for the info window
infowindow.setContent(data);
// show the infowindow
infowindow.open(map, marker);
});
})(marker, data);
}
map.fitBounds(bounds);
}
And the function that's fired onclick that I want to open the corresponding infowindow.
function moveCenter(lat, lng, letter){
google.maps.event.trigger(marker[letter], "click");
}
Any help on how to build a marker object array and have it be seen by my moveCenter function would be greatly appreciated.
Looks like you just need to add this line to your code:
markers[letter] = marker;
and change your function:
function moveCenter(lat, lng, letter){
google.maps.event.trigger(markers[letter], "click");
}
(make sure the markers array is in the global scope)
markers = [];
function addMap(addressesJSON, id){
var addresses = eval('(' + addressesJSON + ')');
var cenLat = 41.677389;
var cenLng = -72.384294;
var latLow = 41.4;
var lngLow = -72.8;
var latHigh = 41.8;
var lngHigh = -71.9;
if (addresses.length){
for (var i in addresses){
addresses[i].lat = parseFloat(addresses[i].lat);
addresses[i].lng = parseFloat(addresses[i].lng);
if (i == 0){
latLow = addresses[i].lat;
latHigh = addresses[i].lat;
lngLow = addresses[i].lng;
lngHigh = addresses[i].lng;
} else {
if (addresses[i].lat < latLow){
latLow = addresses[i].lat;
}
if (addresses[i].lat > latHigh){
latHigh = addresses[i].lat;
}
if (addresses[i].lng < lngLow){
lngLow = addresses[i].lng;
}
if (addresses[i].lng > lngHigh){
lngHigh = addresses[i].lng;
}
}
address = "<span style=\"color: #0000ff\">" + addresses[i].name + "</span><br/>" + addresses[i].address + "<br/>Directions: To - From";
addresses[i].address = address;
}
cenLat = (latLow + latHigh) / 2;
cenLng = (lngLow + lngHigh) / 2;
}
var mapOptions = {
center: new google.maps.LatLng(cenLat, cenLng),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Display a map on the page
var map = new google.maps.Map(document.getElementById(id), mapOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in addresses){
var letter = addresses[i].letter;
var data = addresses[i].address;
var myLatlng = new google.maps.LatLng(addresses[i].lat, addresses[i].lng);
var latlng = new google.maps.LatLng(addresses[i].lat, addresses[i].lng);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: addresses[i].name,
icon: "http://maps.google.com/mapfiles/marker" + letter + ".png"
});
markers[letter] = marker;
(function (marker, data) {
google.maps.event.addListener(marker, "click", function () {
// Center on marker
map.setCenter(marker.getPosition());
// Set the data for the info window
infowindow.setContent(data);
// show the infowindow
infowindow.open(map, marker);
});
})(marker, data);
}
map.fitBounds(bounds);
}
function popupDirections(marker) {
var infowindow = new google.maps.InfoWindow(
{
content:
'Hello World'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
I write this function in order to show the information of place name, street number, or somethings else, but the problem is that I don't know how to get that information to display on the pop up. Any help would be appreciated.
may be you want to try this, this my code that have a element info windows from JSON. but if you only want to write your infowindow, just write it like as tag javascript. in my case, my element of info window, i get from database.
function initialize(){
var x = new Array();
var y = new Array();
var customer_name = new Array();
var cp_rayon_name = new Array();
var icon = new Array();
var photo = new Array();
var city = new Array();
var address = new Array();
var postal_code = new Array();
// posisi default peta saat diload
var petaoption = {
zoom: 5,
center: new google.maps.LatLng( -1.2653859,116.83119999999997),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
//bound
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(7.449624,93.15033),
new google.maps.LatLng(-12.640338,144.830017)
);
var boundLimits = {
maxLat : allowedBounds.getNorthEast().lat(),
maxLng : allowedBounds.getNorthEast().lng(),
minLat : allowedBounds.getSouthWest().lat(),
minLng : allowedBounds.getSouthWest().lng()
};
var lastValidCenter = peta.getCenter();
var newLat, newLng;
google.maps.event.addListener(peta, 'center_changed', function() {
center = peta.getCenter();
if (allowedBounds.contains(center)) {
// still within valid bounds, so save the last valid position
lastValidCenter = peta.getCenter();
return;
}
newLat = lastValidCenter.lat();
newLng = lastValidCenter.lng();
if(center.lng() > boundLimits.minLng && center.lng() < boundLimits.maxLng){
newLng = center.lng();
}
if(center.lat() > boundLimits.minLat && center.lat() < boundLimits.maxLat){
newLat = center.lat();
}
peta.panTo(new google.maps.LatLng(newLat, newLng));
});
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
cp_rayon_name[i] = msg.enseval.customer[i].nama_rayon;
icon[i] = msg.enseval.customer[i].icon;
photo[i] = msg.enseval.customer[i].id_photo;
city[i] = msg.enseval.customer[i].city;
address[i] = msg.enseval.customer[i].address;
postal_code[i] = msg.enseval.customer[i].postal_code;
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
var gambar_tanda = 'assets/images/'+msg.enseval.customer[i].icon+'.png';
var photo_cust ='<img src="assets/images/foto_cust/'+msg.enseval.customer[i].id_photo+'_1.jpg" style="width:200px;height:120px;"/>';
//var nm_cust = msg.enseval.customer[i].nama_customer;
//var nm_rayon = , msg.enseval.customer[i].nama_rayon;
var html = '<b>' + customer_name[i] + '</b><br/>'+city[i]+ ', '+address[i]+', '+postal_code[i]+'<br/>' + cp_rayon_name[i] + '<br/>' + photo_cust;
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, html );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
function reload(form){
var val=form.org_id.options[form.org_id.options.selectedIndex].value;
self.location='main_page_admin.php?cabang=' + val ;
}