Display multiple routes on google map - google-maps

I am trying to show multiple routes on google map but It is showing only one. Can you please what I am doing wrong?
<div class="searchmap" style="float:left;margin-left:1%" id="map"></div>
var map = null;
var markerPoints = [];
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById("map"), {scrollwheel:false, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, center:new google.maps.LatLng(19.0759837, 72.87765590000004), zoom:13});
directionsDisplay.setMap(map);
}
function calcRoute(flat, flng, tlat, tlng)
{
var start = new google.maps.LatLng(flat, flng);
var end = new google.maps.LatLng(tlat, tlng);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false,
suppressInfoWindows: true
});
directionsDisplay.setMap(map);
directionsService.route(request, function(result, status) {
console.log(result);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
calcRoute("19.210430", "72.843422", "19.109858", "72.878433");
calcRoute("19.228977", "72.856812", "19.117302", "72.884041");
Can you please let me know what I am doing wrong?

Display multiple routes on google map with waypoints and direction arrow
==============
Click here!
![In image u can see 2 routes with direction arrow][1]
<style>
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var stops_data = [[ {"Geometry":{"Latitude":23.05242,"Longitude":72.53375}},
{"Geometry":{"Latitude":23.03007,"Longitude":72.59664}}
] ,[ {"Geometry":{"Latitude":23.00959,"Longitude":72.56189}},
{"Geometry":{"Latitude":23.05754,"Longitude":72.55302}}
]];
var a,z,b;
var add;
var speed = 0.000005, wait = 1;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
var myPano;
var panoClient;
var nextPanoId;
var directionsDisplay = [];
directionsDisplay[0] = new window.google.maps.DirectionsRenderer({
suppressMarkers: true
});
directionsDisplay[1] = new window.google.maps.DirectionsRenderer({
suppressMarkers: true
});
var map;
var mapOptions = { center: new google.maps.LatLng(42.5584308, -70.8597732), zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize()
{
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsService = new google.maps.DirectionsService();
// Setroute(locations[0],locations[1],directionsDisplay[0]);
// Setroute(locations2[0],locations2[1],directionsDisplay[1]);
Tour_startUp(stops_data[0]);
window.tour.loadMap(map, directionsDisplay[0]);
window.tour.fitBounds(stops_data[0],map);
if (stops_data[0].length > 1)
window.tour.calcRoute(stops_data[0],directionsService, directionsDisplay[0]);
Tour_startUp(stops_data[1]);
window.tour.loadMap(map, directionsDisplay[1]);
window.tour.calcRoute(stops_data[1],directionsService, directionsDisplay[1]);
window.tour.fitBounds(stops_data[1],map);
}
function fx(o)
{
if(o && o.legs)
{
for(l=0;l<o.legs.length;l++)
{
var leg=o.legs[l];
for(var s=0;s<leg.steps.length;++s)
{
var step=leg.steps[s],
a=(step.lat_lngs.length)?step.lat_lngs[0]:step.start_point,
z=(step.lat_lngs.length)?step.lat_lngs[1]:step.end_point,
dir=((Math.atan2(z.lng()-a.lng(),z.lat()-a.lat())*180)/Math.PI)+360,
ico=((dir-(dir%3))%120);
new google.maps.Marker({
position: a,
icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/dir_'+ico+'.png',
new google.maps.Size(24,24),
new google.maps.Point(0,0),
new google.maps.Point(12,12)
),
map: map,
title: Math.round((dir>360)?dir-360:dir)+'°'
});
}
}
}
}
function Tour_startUp(stops) {
// alert('first'+stops.length);
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, dirdis) {
var myOptions = {
zoom: 15,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
dirdis.setMap(map);
},
fitBounds: function (stops_data,map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
for( var x in stops_data) {
var myLatlng = new window.google.maps.LatLng(stops_data[x].Geometry.Latitude, stops_data[x].Geometry.Longitude);
bounds.extend(myLatlng);
}
map.fitBounds(bounds);
},
calcRoute: function (stops_new,directionsService, dirdis) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops_new.length > 0;
var time= [];
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
// alert('second'+stops_new.length);
//alert(stops_new[0].Geometry.Latitude +' ===== ' +stops_new[0].Geometry.Longitude);
for (var j = itemsCounter; j < stops_new.length; j++) {
subitemsCounter++;
//alert(stops[j].Geometry.Time);
subBatch.push({
location: new window.google.maps.LatLng(stops_new[j].Geometry.Latitude, stops_new[j].Geometry.Longitude),
stopover: true
});
//time.push(stops[j].Geometry.Time);
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops_new.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;
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
};
// alert('start'+start);
// alert('end'+end);
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
fx(result.routes[0]);
polyline[0] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
poly2[0] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
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++;
}
}
}
dirdis.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var path = combinedResults.routes[0].overview_path;
//alert(path.length);
// alert(legs.length);
//setRoutes(legs[0].start_location,legs[legs.length-1].end_location);
for (var i=0; i < legs.length;i++)
{
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
if (i == 0) {
//marker[0] = createMarker2(legs[i].start_location,"start",legs[i].start_address,"green");
}
var steps = legs[i].steps;
// alert('arrival time : '+legs[i].arrival_time.text);
// var duration = steps.duration_in_traffic;
// alert(duration.text);
for (j=0;j<steps.length;j++)
{
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++)
{
polyline[0].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
// createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
// Marker for start point
createMarker(dirdis.getMap(),legs[0].start_location,"marker"+0,"Start Point<br>"+legs[0].start_address,'A');
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
// marker for End Point
createMarker(dirdis.getMap(),legs[legs.length-1].end_location,"marker"+i,"End Point <br>"+legs[legs.length-1].end_address,'B');
polyline[0].setMap(map);
//startAnimation(0);
}
}
});
})(k);
}
}
};
}
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) {
//alert(iconStr);
if ((typeof(iconStr)=="undefined") || (iconStr==null)) {
iconStr = "red";
}
if(iconStr == 'A')
{
// for start point
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-start.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 6,20.
new google.maps.Point(9, 34));
}
}
if (iconStr == 'B')
{
// for end point
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-end.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 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 iconImage = 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));
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, html, color) {
//alert(color);
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
// alert('creatMarker'+contentString);
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: getMarkerImage(color),
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;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>
[1]: http://i.stack.imgur.com/yB4Tw.png

Here you go.. the full explaination , credit goes to the author
function drawMap() {
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = new google.maps.LatLng(51.47482547819850,-0.37739553384529);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
requestDirections('(51.47482547819850,-0.37739553384529)', '(51.59512428598160,-0.17190814889409)');
requestDirections('EC1V 0AH', '(51.47615506206120, -0.37795315370703)');
}
you need to create an instance of google.maps.DirectionsRenderer(); EVERYTIME you draw the route to make it visible ;)

Your directionsDisplay variable is an instance of google.maps.DirectionsRenderer() and that can only hold one set of directions at a time. If you want to display more than one route, you need multiple google.maps.DirectionsRenderer().

To get multiple routes we can add provideRouteAlternatives = true inside request object while calling route() of DirectionsService object. See Directions Requests.
This method will return array of routes if available with their name in summary key.
Now we can display these routes on view and on click of each route we can pass route object and can render the direction by setDirections() of DirectionsRenderer object. See Displaying the DirectionsResult

try this code
<!DOCTYPE html>
<html>
<head>
<title>Waypoints in Directions</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=your-key&callback=initMap&libraries=&v=weekly"
defer
></script>
<style type="text/css">
html,
body {
height: 99%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
float: left;
width: 99%;
height: 100%;
}
</style>
<script>
"use strict";
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: {
lat: 19.8762,
lng: 75.3433
}
});
const directionsService = new google.maps.DirectionsService();
let points = [
{
origin: {
lat: 19.9974533,
lng: 73.78980229999999
},
destination: {
lat: 19.0759837,
lng: 72.8776559
},
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
},
{
origin: {
lat: 21.1458,
lng: 79.0882
},
destination: {
lat: 18.5204,
lng: 73.8567
},
// waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}
]
for (var i = 0; i < points.length; i++) {
calculateAndDisplayRoute(directionsService,points[i])
}
function calculateAndDisplayRoute(directionsService,points) {
let directionsRenderer = new google.maps.DirectionsRenderer();
// const waypts = [{
// location: {
// lat: 19.8762,
// lng: 75.3433
// },
// },
// ];
directionsService.route(
points,
(response, status) => {
console.log(response);
if (status === "OK") {
directionsRenderer.setDirections(response);
directionsRenderer.setMap(map);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
}
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Related

Google maps displaying other side of the planet

I have literally been trying anything and everything, but the map displays somewhere in Antarctica, when the coordinates that I am receiving, are for cities in the US.
The following is the code that inits the map:
$(window).on('load', function() {
// eslint-disable-next-line
function initTest() {
var fastestCitiesApi = JSON.parse(document.getElementById('fastestCitiesApi').value);
console.log(fastestCitiesApi);
var tempLatLng = fastestCitiesApi[0]['latLng'];
console.log(tempLatLng);
var latLng = tempLatLng.split(',');
console.log('latLng[0]: ' + latLng[0]);
console.log('latLng[1]: ' + latLng[1]);
const myLatLng = new google.maps.LatLng({ lat: parseFloat(latLng[0]), lng: parseFloat(latLng[1]) });
const mapOptions = {
zoom: 4,
center: myLatLng
};
const map = new google.maps.Map(document.getElementById('fastest_cities_map'), mapOptions);
new google.maps.Marker({
position: myLatLng,
map,
title: 'somewhere',
});
}
initTest();
});
As you can see by the following screen shot of the console is showing, that the coordinates are 36, 78 - which when I do a look up on google for Boydton, VA - those are the coordinates that is returned - link to google search for Boydton, VA lat long
As you can see by the screen shot, I have zero errors. What am I doing wrong?
Thanks in advance
Thanks to #Gray pointing out that the long should be negative, the rest of the array loaded up the markers as expected.
Here's the final code:
$(window).on('load', function() {
// eslint-disable-next-line
function initTest() {
/* init vars */
const map = new google.maps.Map(document.getElementById('fastest_cities_map'));
var fastestCitiesApi = JSON.parse(document.getElementById('fastestCitiesApi').value);
// console.log(fastestCitiesApi);
var tempLatLng = '';
var latLng = [];
var markerOptionsArray = new Array();
var latlngArray = new Array();
var myLat = new Array();
var myLng = new Array();
var markers = [];
var nameArray = [];
var infowindow = new google.maps.InfoWindow({maxWidth: 350});
/* create arrays for markers */
for(var item in fastestCitiesApi) {
tempLatLng = fastestCitiesApi[item]['latLng'];
nameArray.push(fastestCitiesApi[item]['city']);
// console.log(tempLatLng);
latLng = tempLatLng.split(',');
myLat.push(latLng[0]);
myLng.push(latLng[1]);
// console.log('latLng[0]: ' + latLng[0]);
// console.log('latLng[1]: ' + latLng[1]);
markers.push({
lat: myLat[item],
lng: myLng[item],
name: nameArray[item],
});
}
// console.log('markers: ' + JSON.stringify(markers));
var bounds = new google.maps.LatLngBounds();
for (var v=0; v<markers.length; v++)
{
var secheltLoc = new google.maps.LatLng(markers[v].lat, markers[v].lng);
var myOptions = {
content: markers[v].name
,boxStyle: {
border: "none"
,textAlign: "center"
,fontSize: "12pt"
,width: "120px"
}
,disableAutoPan: true
,pixelOffset: new google.maps.Size(-50, 0)
,position: secheltLoc
,closeBoxURL: ""
,isHidden: false
,pane: "mapPane"
,enableEventPropagation: true
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[v].lat, markers[v].lng),
map: map,
center: new google.maps.LatLng(markers[v].lat, markers[v].lng)
});
google.maps.event.addListener(marker, 'click', (function (marker, v) {
return function () {
infowindow.setContent(markers[v].name);
infowindow.open(map, marker);
}
})(marker, v));
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
marker.open = false;
});
bounds.extend(new google.maps.LatLng(markers[v].lat, markers[v].lng));
myLatLng = markers[v].lat+','+markers[v].lng;
}
map.fitBounds(bounds);
}
// alert(google.maps.Map);
initTest();
});
The following is a screen shot of the result of the eight city array:

Unable to get Polyline from route

I am trying to animate a polyline on top of hidden Route (with strokeWeight: 0) and animate it on this example but not sure why I am not able to grab the correct points on .interpolate() method.
What am I doing wrong?
<script src="https://maps.googleapis.com/maps/api/js?key=xxx&libraries=geometry"></script>
var map;
$(document).ready(function() {
var latlng = new google.maps.LatLng(49.241943, -122.889318);
var myOptions = {
zoom: 12,
center: latlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map_canvas').get(0), myOptions);
//Starting Direction Services
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
});
directionsService.route({
origin: new google.maps.LatLng(49.241943, -122.889318),
destination: new google.maps.LatLng(49.241943, -122.999999),
waypoints: [{
stopover: false,
location: new google.maps.LatLng(49.241943, -122.889318)
}],
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
var polyline = new google.maps.Polyline({
path: [],
strokeColor: 'red',
strokeWeight: 0
});
var bounds = new google.maps.LatLngBounds();
var line = response.routes[0].legs;
for (i = 0; i < polyline.length; i++) {
var steps = polyline[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
var step = 0;
var numSteps = 250;
var timePerStep = 5;
var interval = setInterval(function() {
step += 1;
if (step > numSteps) {
clearInterval(interval);
} else {
var are_we_there_yet = google.maps.geometry.spherical.interpolate(line, step / numSteps);
line.setPath([polyline, are_we_there_yet]);
}
}, timePerStep);
line.setMap(map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
The interpolate function takes these three parameters, according to the docs:
from: LatLng,
to: LatLng,
fraction: number
You're passing it the following two parameters:
google.maps.geometry.spherical.interpolate(line, step / numSteps)
And instead of passing the whole line, you should do something like:
google.maps.geometry.spherical.interpolate(latLng1, latLng2, step / numSteps)
... where latLng1 and latLng2 would be the endpoints of your line I guess.
You're also doing this... you create a Polyline, polyline. Then you get a line. But you then try and loop over polyline.length:
var polyline = new google.maps.Polyline({
path: [],
strokeColor: 'red',
strokeWeight: 0
});
var line = response.routes[0].legs;
for (i = 0; i < polyline.length; i++) {
I think that last line (and other references inside the nested loops) should refer to the line not the polyline, i.e.
for (i = 0; i < line.length; i++) {

Google map markers are not visible when loading map in dialog box [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to load google map in dialog box on click of a button. Everything is loading except markers. Please help me what is wrong in my code. How to show markers. When i do not use dialog box then its working fine.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService;
var map;
var stepDisplay;
var image ;
var geocoder;
var latitude;
$(function () {
$("#btnShow").click(function () {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function () {
$(this).dialog('close');
}
},
open: function () {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsService = new google.maps.DirectionsService();
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
directionsDisplay.setMap(map);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
//supress default markers and set route color
directionsDisplay.setOptions( { suppressMarkers: true,
polylineOptions: {
strokeWeight: 5,
strokeOpacity: 1,
strokeColor: 'green'
}
} );
calcRoute();
}
});
});
});
var cList= [];
function showOnMap(){
cList = [];
var coordinates = [];
coordinates.push("ORG");
coordinates.push("18.9542149");
coordinates.push("72.81203529999993");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
coordinates = [];
coordinates.push("DEST");
coordinates.push("19.2147067");
coordinates.push("72.91062020000004");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
}
function calcRoute() {
var start;
var end;
var temp;
var waypts = [];
for(var i =0;i<cList.length;i++){
var coord = cList[i];
if(coord[0] == "ORG"){
start = coord[1] +", "+coord[2];
alert("start: "+start);
showSteps(coord[1] , coord[2], coord[3]);
}else if(coord[0]== "DEST"){
end = coord[1] +", "+coord[2];
alert("end: "+end);
showSteps(coord[1] , coord[2],coord[3]);
}else if(coord[0]== "WAYPOINT"){
$("#comments").text("WAYPOINT: ");
temp = coord[1] +", "+coord[2];
//alert("way: "+temp);
waypts.push({
location:temp,
stopover:true});
var text = "reached till this stop ";
showSteps(coord[1] , coord[2],text);
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var marker;
function showSteps(lat, lon, text) {
//alert("showSteps:"+image+" text"+text);
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lon),
map: map
});
attachInstructionText(marker, text);
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
if(text == ""){
text = "not reached";
}
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
<input id = "btnShow" type="button" value="Show Maps" class="fMap" onclick="showOnMap()" />
<div id="dialog" style="display: none">
<div id="dvMap" style="height: 380px; width: 580px;">
</div>
</div>
Your map variable is local to the open function for the dialog:
open: function() {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
Remove the "var" from the beginning of the line that instantiates the google.maps.Map object.
working fiddle
code snippet:
var directionsDisplay;
var directionsService;
var map;
var stepDisplay;
var image;
var geocoder;
var latitude;
$(function() {
$("#btnShow").click(function() {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function() {
$(this).dialog('close');
}
},
open: function() {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsService = new google.maps.DirectionsService();
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map($("#dvMap")[0], mapOptions);
directionsDisplay.setMap(map);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
//supress default markers and set route color
directionsDisplay.setOptions({
suppressMarkers: true,
polylineOptions: {
strokeWeight: 5,
strokeOpacity: 1,
strokeColor: 'green'
}
});
calcRoute();
}
});
});
});
var cList = [];
function showOnMap() {
cList = [];
var coordinates = [];
coordinates.push("ORG");
coordinates.push("18.9542149");
coordinates.push("72.81203529999993");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
coordinates = [];
coordinates.push("DEST");
coordinates.push("19.2147067");
coordinates.push("72.91062020000004");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
}
function calcRoute() {
var start;
var end;
var temp;
var waypts = [];
for (var i = 0; i < cList.length; i++) {
var coord = cList[i];
if (coord[0] == "ORG") {
start = new google.maps.LatLng(coord[1], coord[2]);
showSteps(coord[1], coord[2], coord[3]);
} else if (coord[0] == "DEST") {
end = new google.maps.LatLng(coord[1], coord[2]);
showSteps(coord[1], coord[2], coord[3]);
} else if (coord[0] == "WAYPOINT") {
$("#comments").text("WAYPOINT: ");
temp = coord[1] + ", " + coord[2];
waypts.push({
location: temp,
stopover: true
});
var text = "reached till this stop ";
showSteps(coord[1], coord[2], text);
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var marker;
function showSteps(lat, lon, text) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map
});
attachInstructionText(marker, text);
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
if (text == "") {
text = "not reached";
}
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">
<input id="btnShow" type="button" value="Show Maps" class="fMap" onclick="showOnMap()" />
<div id="dialog" style="display: none">
<div id="dvMap" style="height: 380px; width: 580px;">
</div>
</div>

Google Maps and RouteBoxer will not display polygon lines

Thanks in advance for any help you can provide! I'm using RouteBoxer in Google Maps API V3, but for some reason I can't get the lines to appear. I'm concerned that the function isn't running at all, and it's necessary for the next step of my project: passing lat and long to find pois along the route. Seeing the lines on the map will help me make sure it's running correctly.
Here is my code
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var routeBoxer = null;
var boxpolys = null;
var rdistance = 20; // km
function initialize() {
//directionspanelstuff
//directionsdisplaystuff
//mapoptions
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
routeBoxer = new RouteBoxer();
}
function calcRoute() {
//startendwaypoints
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
// Box the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, rdistance);
clearBoxes();
drawBoxes(boxes);
for (var i = 0; i < boxes.length; i++) {
var bounds = box[i];
// Perform search over this bounds
}
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
</script>
There are 4 javascript errors pointed out by the javascript console:
mapOptions is not defined (probably not a real problem)
directionsDisplay is null (not initialized)
result is undefined (typo, or cut and paste error)
box is undefined (typo)
working example
code snippet:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var routeBoxer = null;
var boxpolys = null;
var rdistance = 20; // km
function initialize() {
//directionspanelstuff
//directionsdisplaystuff
//mapoptions
map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 10,
center: new google.maps.LatLng(41.084951, 29.016048),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
routeBoxer = new RouteBoxer();
calcRoute();
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
//startendwaypoints
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
// Box the overview path of the first route
var path = response.routes[0].overview_path;
var boxes = routeBoxer.box(path, rdistance);
clearBoxes();
drawBoxes(boxes);
for (var i = 0; i < boxes.length; i++) {
var bounds = boxes[i];
// Perform search over this bounds
}
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/routeboxer/src/RouteBoxer.js"></script>
<input id="start" type="text" onchange="calcRoute();" value="chicago, il"></input>
<input id="end" type="text" onchange="calcRoute();" value="st louis, mo"></input>
<div id="map_canvas" style="height: 400px; width:500px;"></div>
<div id="info"></div>

Google Maps V3 - waypoints + infowindow with random text

I'm using this example to set up a route with more then 8 markers.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Directions Waypoints</title>
<style>
#map{
width: 100%;
height: 450px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
jQuery(function() {
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
] ;
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();
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);
});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
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.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.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;
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);
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);
}
}
});
})(k);
}
}
};
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
It works like a charm but I have problem to setup an infowindow for each waypoint. I would like to leave markers names like A , B ,C or generate it in otherway but to keep A,B,C or 1,2,3 pattern and I want to add infowindow to each marker which contains title text and link.
I was trying to find any info or examples but nothing works. Maybe someone have and idea how to easily add infowindow to this code.
Here is an example that draws the directions from scratch with custom markers and infowindows:
Example
If you use the suppressInfoWindows option on the DirectionsRenderer, you can just use the part of it that creates the markers and their associated infowindows.
Working example based on your code
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Directions Waypoints</title>
<style>
#map{
width: 100%;
height: 450px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
jQuery(function() {
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
] ;
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});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);
});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
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.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.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;
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);
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;
// alert(legs.length);
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,"marker"+i,"some text for the "+i+"marker<br>"+legs[legs.length-1].end_address,markerletter);
}
}
});
})(k);
}
}
};
}
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) {
if ((typeof(iconStr)=="undefined") || (iconStr==null)) {
iconStr = "red";
}
if (!icons[iconStr]) {
icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/marker"+ iconStr +".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 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 iconImage = 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));
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, html, color) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: getMarkerImage(color),
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;
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>