Display a route without DirectionsRenderer in Google Map V3 - google-maps

I'm trying to draw my own route without a DirectionsRenderer.
Here is my code:
var map;
var directionsService;
function initialize() {
var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsService = new google.maps.DirectionsService();
calcRoute();
}
function calcRoute() {
var request = {
origin: 'שדי חמד',
destination: 'כפר סבא',
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
map.fitBounds(directionResult.routes[0].bounds);
createPolyline(response);
}
});
}
function createPolyline(directionResult) {
var line = new google.maps.Polyline({
path: directionResult.routes[0].overview_path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 4
});
line.setMap(map);
for (var i = 0; i < line.getPath().length; i++) {
var marker = new google.maps.Marker({
icon: { path: google.maps.SymbolPath.CIRCLE, scale: 3 },
position: line.getPath().getAt(i),
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
All I get is a gray window, not even a map.
When sending the DirectionsService's response to the DirectionsRenderer I get both polylines.
Any advice will be welcome.

I get a javascript error "directionResult is undefined"
on this line:
map.fitBounds(directionResult.routes[0].bounds);
If I fix that (change it to response) it works.
working example
BTW - I would not suggest using overview_path; if the path is long or complex, that doesn't have enough detail in it.
code snippet:
var map;
var directionsService;
function initialize() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsService = new google.maps.DirectionsService();
calcRoute();
}
function calcRoute() {
var request = {
origin: 'שדי חמד',
destination: 'כפר סבא',
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
map.fitBounds(response.routes[0].bounds);
createPolyline(response);
}
});
}
function createPolyline(directionResult) {
var line = new google.maps.Polyline({
path: directionResult.routes[0].overview_path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 4
});
line.setMap(map);
for (var i = 0; i < line.getPath().length; i++) {
var marker = new google.maps.Marker({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3
},
position: line.getPath().getAt(i),
map: map
});
}
}
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"></script>
<div id="map-canvas"></div>

Related

How to show polyline in the order of waypoints in google maps?

I want to show polyline in the order of waypoints. Consider I want to travel from A(source) to C(destination) through B(mid point), then the polyline should also be shown in the same order. But my code not working correctly. The polyline should be drawn in the order of A, B, and C.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyBkDLA8MD77ueEwwxMgxadTBtzjgU0fJE0"></script>
<script>
// The below code shows polyline incorrectly
var map;
var wyPts = [];
function addWayPoints(location) {
wyPts.push({
location: location,
stopover: true
});
}
function createInfoWindowContent(latLng, contentStr) {
var content = '<p><b>' + contentStr + ' </b> </p>' + 'LatLng: ' + latLng;
return content;
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: wyPts,
optimizeWaypoints: false,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
}
else {
alert('Could not display directions due to: ' + status);
}
}
);
}
function initMap() {
var src = new google.maps.LatLng(17.45165, 78.3942433);
var midPt1 = new google.maps.LatLng(17.4510881, 78.3932577);
addWayPoints(midPt1);
var destination = new google.maps.LatLng(17.4517866, 78.3927456);
map = new google.maps.Map(document.getElementById('map'), {
center: src,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT,
mapTypeIds: [google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.HYBRID]
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoom: 14
});
/*var coordInfoWindowSrc = new google.maps.InfoWindow({
content: createInfoWindowContent(src, "Source"),
maxWidth: 180
});
coordInfoWindowSrc.setPosition(src);
coordInfoWindowSrc.open(map);
var coordInfoWindowDest = new google.maps.InfoWindow({
content: createInfoWindowContent(destination, "Destination"),
maxWidth: 180
});
coordInfoWindowDest.setPosition(destination);
coordInfoWindowDest.open(map);*/
var polylineProps = {
strokeColor: '#009933',
strokeOpacity: 1.0,
strokeWeight: 3
};
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: false,
map: map,
suppressMarkers: false,
polylineOptions: polylineProps
});
var directionsService = new google.maps.DirectionsService();
displayRoute(src, destination, directionsService, directionsDisplay);
directionsDisplay.addListener(
'change',
function () {
displayRoute(src, destination, directionsService,
directionsDisplay);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<html>
<div id="map" style="width:100%; height:90vh;">
<div id="map-canvas" style="width:100%; height:100%;"></div>
<div id="crosshair"></div>
</div>
</html>
Your code is doing exactly what you are coding it to do. The route goes from the source (S) to the midpoint (M) then (backtracks) to the destination (D, which is between the start and midpoints). You just can't see the overlap of the route because it overlays the original route. Look at the description of the route in the directions "panel".
proof of concept fiddle
code snippet:
var map;
var wyPts = [];
function addWayPoints(location) {
wyPts.push({
location: location,
stopover: true
});
}
function createInfoWindowContent(latLng, contentStr) {
var content = '<p><b>' + contentStr + ' </b> </p>' + 'LatLng: ' + latLng;
return content;
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: wyPts,
optimizeWaypoints: false,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
}
);
}
function initMap() {
var src = new google.maps.LatLng(17.45165, 78.3942433);
var midPt1 = new google.maps.LatLng(17.4510881, 78.3932577);
addWayPoints(midPt1);
var destination = new google.maps.LatLng(17.4517866, 78.3927456);
map = new google.maps.Map(document.getElementById('map'), {
center: src,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT,
mapTypeIds: [google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.HYBRID
]
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoom: 14
});
var markerS = new google.maps.Marker({
map: map,
position: src,
title: "Source",
label: "S"
});
var markerD = new google.maps.Marker({
map: map,
position: destination,
title: "Dest",
label: "D"
});
var markerM = new google.maps.Marker({
map: map,
position: midPt1,
title: "Mid",
label: "M"
});
var polylineProps = {
strokeColor: '#009933',
strokeOpacity: 1.0,
strokeWeight: 3
};
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: false,
map: map,
suppressMarkers: true,
polylineOptions: polylineProps
});
directionsDisplay.setPanel(document.getElementById("panel"));
var directionsService = new google.maps.DirectionsService();
displayRoute(src, destination, directionsService, directionsDisplay);
directionsDisplay.addListener(
'change',
function() {
displayRoute(src, destination, directionsService,
directionsDisplay);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map" style="width:100%; height:90vh;"></div>
<div id="panel">
</div>
The order, for instance, is A....I, where A is the origin, I is the destination and [B-H] are waypoints.
In your code you just need to swap the coordinates of the midpoint and destination
var midPt1 = new google.maps.LatLng(17.4517866, 78.3927456);
...
var destination = new google.maps.LatLng(17.4510881, 78.3932577);

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>

Uncaught TypeError: Cannot read property 'length' of null

I used google map javascript V3 API for this module.
This code working fine untill we don't drag the map, but when i drag the map i'll get "Uncaught TypeError: Cannot read property 'length' of null "(from google chrome inspect element)
Code:
<html>
<head>
<title>
Google Search
</title>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0;}
#map-canvas { height: 80%; width:80%; margin: auto; padding: 0;}
</style>
<script src="js/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script>
var map;
var service;
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(initialize);
});
function initialize(location) {
console.log(location);
var currentlocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOptions = {
center: currentlocation ,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
draggable: true
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: currentlocation,
map: map,
title:"Hello World!"
});
service = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'bounds_changed', performSearch);
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.25,
map: map,
center: currentlocation,
radius: 10000
};
var circle = new google.maps.Circle(circleOptions);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
name: "McDonald's"
};
service.nearbySearch(request, handleSearchResult);
}
function handleSearchResult(results, status){
console.log(results);
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
position: results[i].geometry.location,
map: map,
icon: "images//restaurant-71.png"
});
}
}
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
You aren't checking the return status of the places search. If it encounters an error (or doesn't return any results), it will fail.
function handleSearchResult(results, status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
position: results[i].geometry.location,
map: map,
icon: "images//restaurant-71.png"
});
}
else { alert("no results"); }
}

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>