Reputation: 849
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.
Upvotes: 2
Views: 11341
Reputation: 161334
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.
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>
Upvotes: 5