Draggable snap to road distance markers - google-maps

I am using some helpful code I found at http://exploregooglemaps.blogspot.com.br/2012/02/measuring-distance-with-markers.html to add markers and measure distance.
I would like the markers to snap to road by default, but when the users holds the shift key a direct line is used.
I have managed to implement the if statement for the shift key, and a path is drawn when I hold the shift key, however no snap to road path is drawn by default.
I am calling two functions, one to draw a straight line drawPath and one to draw a snap to road line drawPathD
Any help would be much appreciated.
<code>
var map,
service = new google.maps.DirectionsService(),
shiftPressed = false,
poly;
var path = [];
shiftPressed = false;
var markers = [];
var routePoints = [];
google.maps.event.addDomListener(document, "keydown", function () {
shiftPressed = true;
});
google.maps.event.addDomListener(document, "keyup", function () {
shiftPressed = false;
});
function $(id) {
return document.getElementById(id);
}
var map;
var mapOptions = {
center: new google.maps.LatLng(-23.5489433, - 46.6388182),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var markers = [];
var line;
function initialize() {
map = new google.maps.Map($("map_canvas"), mapOptions);
line = new google.maps.Polyline({
map: map,
strokeColor: "#FF3333",
strokeOpacity: 0.5,
strokeWeight: 8
});
google.maps.event.addListener(map, 'click', function (event) {
var marker = new google.maps.Marker({
map: map,
position: event.latLng,
draggable: true
});
if (shiftPressed) {
markers.push(marker);
drawPath();
} else {
markers.push(marker);
drawPathD();
}
google.maps.event.addListener(marker, 'dblclick', function (event) {
marker.setMap(null);
drawPath();
});
google.maps.event.addListener(marker, 'drag', function (event) {
drawPath();
});
});
}
function countMarkers() {
count = 0;
for (var i = routePoints.length - 1; i >= 0; i--) {
if (markers[i].getMap() == null) {
routePoints.splice(i, 1);
} else {
count++;
}
}
return count;
}
function drawPath() {
countMarkers();
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
line.setPath(coords);
meters = google.maps.geometry.spherical.computeLength(coords);
$("distKm").value = Math.round(meters / 1000 * 100) / 100;
$("distMi").value = Math.round(meters / 1609 * 100) / 100;
}
function drawPathD(event) {
countMarkers();
var coords = [];
service.route({
origin: path[path.length - 1],
destination: event.latLng,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
path = path.concat(result.routes[0].overview_path);
routePoints.setPath(path);
}
});
meters = google.maps.geometry.spherical.computeLength(coords);
$("distKm").value = Math.round(meters / 1000 * 100) / 100;
$("distMi").value = Math.round(meters / 1609 * 100) / 100;
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null)
}
drawPath();
}
google.maps.event.addDomListener(window, 'load', initialize);
</code>

Here's how to implement the "Snap to Road" functionality in Google Maps API v3:
polyline snap to road using google maps api v3

Related

Google maps v3 - Add markers at the center of tiles

function initialize() {
var myLatlng;
var mapOptions;
myLatlng = new google.maps.LatLng(29.98439980, -95.34140015);
mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
drawRectangle(map);
var result = {"regionList":[{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578}]};
alert(result);
addMarkersAtRegionCenter(map, result);
});
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for(var i=0; i<length; i++)
{
var image = result.regionList[i].imageIcon;
//alert("Latitude : " + result.regionList[i].centerLatitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude,result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() {
window.location.href = marker.url;
}
})(marker, i));
}
}
function drawRectangle(map) {
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var numberOfParts = 4;
var tileWidth = (northEast.lng() - southWest.lng()) / numberOfParts;
var tileHeight = (northEast.lat() - southWest.lat()) / numberOfParts;
for (var x = 0; x < numberOfParts; x++) {
for (var y = 0; y < numberOfParts; y++) {
var areaBounds = {
north: southWest.lat() + (tileHeight * (y+1)),
south: southWest.lat() + (tileHeight * y),
east: southWest.lng() + (tileWidth * (x+1)),
west: southWest.lng() + (tileWidth * x)
};
var area = new google.maps.Rectangle({
strokeColor: '#FF0000',
//strokeOpacity: 0.8,
strokeWeight: 2,
//fillColor: '#FF0000',
//fillOpacity: 0.35,
map: map,
bounds: areaBounds
});
}
}
}
}
google.maps.event.addDomListener(window, "load", initialize);
In the above code, I am trying to add markers at the center of each rectangle. But I am not able to add markers. I have hard coded image icon value since I don't have image mentioned in the array.
Thanks in advance for your help.
Related question: Google maps api v3 - divide region into equal parts using tiles
Simpler to add the markers to the centers of the rectangles when you create them:
var centerMark = new google.maps.Marker({
position: area.getBounds().getCenter(),
map: map
});
proof of concept fiddle
To add the markers from the response to the map (the positions in the posted response are not at the center of the squares), this is the same function you posted in your question, it works for me (the blue markers), I modified your click listener to open an infowindow (rather than do a redirect of the page):
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for (var i = 0; i < length; i++) {
var image = result.regionList[i].imageIcon;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude, result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// window.location.href = marker.url;
infowindow.setContent("regionList:" + i + "<br>centLat=" + result.regionList[i].centerLatitude + "<br>centLng=" + result.regionList[i].centerLongitude + "<br>imageIcon=" + result.regionList[i].imageIcon + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
})(marker, i));
}
}

Google Maps Api - drawing routes from an array of points

I would like to connect 8 points on google map so that they shared line (road). I would like to click on the point cloud showed up with a description that point. The goal is to show the route the car point to point.
I have script to make map with points but I don't know how connect markers.
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
var flightPath = responseArray.map(function (item) {
return new google.maps.LatLng(item.latitude, item.longitude);
});
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(12);
google.maps.event.removeListener(listener);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
to connect your markers with a google.maps.Polyline (as it looks like you are trying to do).
create an empty array: var flightPlanCoordinates = [];
push the coordinates of the markers (google.maps.LatLng objects) into the array of coordinates you use for the polyline: flightPlanCoordinates.push(marker.getPosition());
set the map option of the polyline: map:map (in the PolylineOptions object).
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
working fiddle
working code snippet:
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
to connect the points using the directions service (from the example you reference)
create an empty array: var flightPlanCoordinates = [];
push the coordinates of the markers (google.maps.LatLng objects) into the array of coordinates you use for the polyline: flightPlanCoordinates.push(marker.getPosition());
use that array to populate the start, end, and waypts arguments into the calcRoute function:
var start = flightPlanCoordinates[0];
var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
var waypts = [];
for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
waypts.push({
location: flightPlanCoordinates[i],
stopover: true
});
}
calcRoute(start, end, waypts);
change the calcRoute function to use those arguments:
function calcRoute(start, end, waypts) {
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
working fiddle
working code snippet:
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
directionsDisplay.setMap(map);
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
// directions service configuration
var start = flightPlanCoordinates[0];
var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
var waypts = [];
for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
waypts.push({
location: flightPlanCoordinates[i],
stopover: true
});
}
calcRoute(start, end, waypts);
}
}
function calcRoute(start, end, waypts) {
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 route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
<div id="directions_panel"></div>

Polylines is not coming perfectly on google map in ios [duplicate]

I am trying to get a polyline on a Google map after getting directions. I want to use the v3_epoly to place markers along a polyline.
I found this post, which worked, but I found it wasn't completely accurate. In the image, the Google directions is the light blue and the polyline is the darker blue:
You can see it's quite inaccurate.
This is the code:
directions_service.route(req, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
path = response.routes[0].overview_path;
$(path).each(function(index, item) {
route.getPath().push(item);
bounds.extend(item);
});
route.setMap(map);
map.fitBounds(bounds);
directions_display.setDirections(response);
}
});
Anyone know either how to improve this accuracy or to get the polyline another way?
EDIT:
I wanted to add the code that got it working:
legs = response.routes[0].legs;
$(legs).each(function(index, item) {
steps = item.steps;
$(steps).each(function(index, item) {
path = item.path;
$(path).each(function(index, item) {
route.getPath().push(item);
counter++;
bounds.extend(item);
});
});
});
Don't use overview_path for the polyline, it doesn't include all the points, grab the points out of all the legs and use them to create the polyline.
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
var steps = legs[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]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
example
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(51.276092, 1.028938),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
});
directionsService.route({
origin: new google.maps.LatLng(51.269776, 1.061326),
destination: new google.maps.LatLng(51.30118, 0.926486),
waypoints: [{
stopover: false,
location: new google.maps.LatLng(51.263439, 1.03489)
}],
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: '#0000FF',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[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]);
}
}
}
polyline.setMap(map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Display multiple routes on google map

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>

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>