Route inside marker radius Google Maps - google-maps

I need your help
I need to know if in some point my route (A->B) is inside my Marker(C) radius
Is there a way to get some true or false of this event?
The idea of this its make something like Uber Pool algorythm or something close to that
JS:
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
pointC = new google.maps.LatLng(51.2029, -0.1403),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
}),
markerC = new google.maps.Marker({
position: pointC,
title: "point C",
label: "C",
map: map
});
var circle = new google.maps.Circle({
map: map,
radius: 1000, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', markerC, 'position');
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
avoidTolls: true,
avoidHighways: false,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
initMap();
HTML
<div id="map-canvas"></div>
CSS
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
HereĀ“s the fiddle
Tks a lot

Process through all the points in the returned directions polyline, check if any of them are in the circle.
// convert the directions response to polylines
renderDirectionsPolylines(response);
// check to see if any of the points from the route are in the circle
for (var i = 0; i < polylines.length; i++) {
for (var j = 0; j < polylines[i].getPath().getLength(); j++) {
if (google.maps.geometry.spherical.computeDistanceBetween(polylines[i].getPath().getAt(j), circle.getCenter()) < circle.getRadius()) {
console.log("route intersects circle at:" + polylines[i].getPath().getAt(j).toUrlValue(6));
}
}
}
proof of concept fiddle
code snippet:
var map;
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
pointC = new google.maps.LatLng(51.2029, -0.1403),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
}),
markerC = new google.maps.Marker({
position: pointC,
title: "point C",
label: "C",
map: map
});
var circle = new google.maps.Circle({
map: map,
radius: 1000, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', markerC, 'position');
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, circle);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, circle) {
directionsService.route({
origin: pointA,
destination: pointB,
avoidTolls: true,
avoidHighways: false,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
renderDirectionsPolylines(response);
console.log("polylines=" + polylines.length);
for (var i = 0; i < polylines.length; i++) {
for (var j = 0; j < polylines[i].getPath().getLength(); j++) {
if (google.maps.geometry.spherical.computeDistanceBetween(polylines[i].getPath().getAt(j), circle.getCenter()) < circle.getRadius()) {
console.log("route intersects circle at:" + polylines[i].getPath().getAt(j).toUrlValue(6));
var mark = new google.maps.Marker({
map: circle.getMap(),
position: polylines[i].getPath().getAt(j),
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
circle.getMap().fitBounds(circle.getBounds());
// document.getElementById('result').innerHTML += "route intersects circle at:"+polylines[i].getPath().getAt(j).toUrlValue(6)+"<br>";
}
}
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
var polylineOptions = {
strokeColor: '#C83939',
strokeOpacity: 1,
strokeWeight: 4
};
var polylines = [];
function renderDirectionsPolylines(response) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
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;
var stepPolyline = new google.maps.Polyline(polylineOptions);
for (k = 0; k < nextSegment.length; k++) {
stepPolyline.getPath().push(nextSegment[k]);
}
polylines.push(stepPolyline);
stepPolyline.setMap(map);
// route click listeners, different one on each step
google.maps.event.addListener(stepPolyline, 'click', function(evt) {
infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
infowindow.setPosition(evt.latLng);
infowindow.open(map);
})
}
}
}
initMap();
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="result"></div>
<div id="map-canvas"></div>

Related

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++) {

Drawing lines from one marker to all other markers and open infowindows of each marker for click

Please click here for screen shot I have Google map which shows the relation between locations based on a condition. What I need is to draw lines from one marker to all other markers and open info windows of each marker for marker click. Can anybody suggest the way to perform the task?
var Markerss = {};
var linearray = [];
function initialize() {
var markers = [{ 'lat': '32.803', 'lon': '-96.7699', 'ExpertsCount': 2, 'Type': 'ofsite' }, { 'lat': '44.9542', 'lon': '-93.1139', 'ExpertsCount': 3, 'Type': 'onsite' }, { 'lat': '32.903', 'lon': '-150.0011', 'ExpertsCount': 5, 'Type': 'offsite' }, { 'lat': '61.85', 'lon': '-97.6501', 'ExpertsCount': 9, 'Type': 'onnsite' }];
var mapProp = {
center: new google.maps.LatLng(28.067768, 2.150065),
zoom: 5,
mapTypeId: 'terrain'
};
//var infowindow = new google.maps.InfoWindow({
// content: "Hello World!"
//});
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var icon = "";
for (i = 0; i <= markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lon));
if (data.Type == "offsite") {
icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
}
else if (data.Type == "onsite") {
icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
}
else {
icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
}
var div = document.createElement('DIV');
div.innerHTML = '<div class="mapicon" id="dvIcon" style="background-image: url(images/mapiconsmall.png);" onmouseover="javascript:$(this).next().show()" onmouseout="javascript:$(this).next().hide()" ><div class="maindiv"style="width:24px;margin-top:3px; text-align:center;margin-left:1px;"><span style="font-weight:bolder;font-size:11px;"> ' + data.ExpertsCount + '</span></div></div><div id="dvExpName" style="display:none;z-index:1;position:absolute;">' + data.expName + '</div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: i,
content: div,
flat: true,
anchor: RichMarkerPosition.MIDDLE,
icon: icon
});
Markerss[i] = marker;
//if (data.Type == "onsite") {
// Marker[i].setClickable = false;
//}
//else {
// Marker[i].setClickable = true;
//}
// Attaching a click event to the current marker
if (markers[i].Type != "onsite") {
google.maps.event.addListener(marker, 'click', function (event) {
if (linearray.length != 0)
{
for (i = 0; i < linearray.length; i++) {
linearray[i].setMap(null);
}
}
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
strokeColor: 'red'
};
for (j = 0; j < markers.length; j++) {
var marker = markers[j];
var lat = parseFloat(markers[j].lat);
var lon = parseFloat(markers[j].lon);
if (lat != event.latLng.lat()) {
var line = new google.maps.Polyline({
path: [{ lat: event.latLng.lat(), lng: event.latLng.lng() }, { lat: lat, lng: lon }],
icons: [{
icon: lineSymbol,
offset: '100%'
}],
strokeColor: 'red',
map: map
});
linearray.push(line);
}
var infoWindow = new google.maps.InfoWindow({
content: '<b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/><b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/>'
});
infoWindow.open(map, Markerss[j]);
}
});
}
}
}

how to draw a google maps waypoint with multi-colored polylines

Hi I try to draw polylines with directions waypoints on google maps .
I tried something like that.
My draw
I want to draw the routes with different colors like this.
Google maps directions example ss
I wrote this sample code .
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [
{
location: '41.062317, 28.899756',
stopover: true
},
{
location: '41.062276, 28.898866',
stopover: true
},
{
location: '41.061993, 28.8982',
stopover: true
}
];
directionsService.route({
origin: {lat: 41.063328, lng:28.901215},
destination:{lat: 41.060756, lng:28.900046},
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setOptions({
directions :response,
})
drawpolylines(directionsDisplay.getMap())
var route = response.routes[0];
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function drawpolylines(map) {
var flightPlanCoordinates = [
{lat: 41.062317, lng: 28.899756},
{lat: 41.062276, lng: 28.898866},
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
You need to create separate polylines for each colored segment. Example below using a modified version of the renderDirectionsPolylines from this related question: Google Maps click event on route (modified to use an array of colors, applying each color to the step in the route of the number).
proof of concept fiddle
code snippet:
var map;
var infowindow = new google.maps.InfoWindow();
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressPolylines: true,
infoWindow: infowindow
});
map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {
lat: 41.85,
lng: -87.65
}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [{
location: '41.062317, 28.899756',
stopover: true
}, {
location: '41.062276, 28.898866',
stopover: true
}, {
location: '41.061993, 28.8982',
stopover: true
}];
directionsService.route({
origin: {
lat: 41.063328,
lng: 28.901215
},
destination: {
lat: 41.060756,
lng: 28.900046
},
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setOptions({
directions: response,
})
var route = response.routes[0];
renderDirectionsPolylines(response, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
var polylineOptions = {
strokeColor: '#C83939',
strokeOpacity: 1,
strokeWeight: 4
};
var colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF"];
var polylines = [];
function renderDirectionsPolylines(response) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
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;
var stepPolyline = new google.maps.Polyline(polylineOptions);
stepPolyline.setOptions({
strokeColor: colors[i]
})
for (k = 0; k < nextSegment.length; k++) {
stepPolyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
polylines.push(stepPolyline);
stepPolyline.setMap(map);
// route click listeners, different one on each step
google.maps.event.addListener(stepPolyline, 'click', function(evt) {
infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
infowindow.setPosition(evt.latLng);
infowindow.open(map);
})
}
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

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>