Tuesday, June 22, 2010

Unfortunatly in google maps api v3 it is not possible to access properties of polylines that represent directions, but it is possible to get points of path that are used do draw this polyline. So if you want to highlight selected direction by changing its color or weight, it is necessary to draw new polyline without using DirectionsRenderer.



So to get information about path we want to display let's get steps from the first route:
    var steps = response.routes[0].legs[0].steps;    

As steps recived from DirectionsService is an two dimensional array, it must be changed into simple array of points:
function createColorPoly(steps){    
var path = Array();
for(var step = 0; step < steps.length; step++){
for(var stepP = 0; stepP < steps[step].path.length; stepP++){
path.push(steps[step].path[stepP]);
}
}

No display this new polyline and add listeners where properties of polyline are changed.

    
var polySelected = {'strokeWeight':'9','strokeColor':'red'};
var polyUnselected = {'strokeWeight':'6','strokeColor':'blue'} ;

var newPoly = new google.maps.Polyline(polyUnselected);
newPoly.setPath(path);
newPoly.setMap(map);
google.maps.event.addListener(newPoly, 'mouseover', function(){newPoly.setOptions(polySelected);});
google.maps.event.addListener(newPoly, 'mouseout', function(){newPoly.setOptions(polyUnselected);});




And this is it :)


Here's the working example example


Here's the full source:
var map;
var myLatLng;
var dirService;

function initialize() {
var latlng = new google.maps.LatLng(40.7694,-73.9542);

myLatLng = latlng;
var myOptions = {
zoom:9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

dirService = new google.maps.DirectionsService();
getDirections();
}
function getDirections(){
var start = 'Broadway, New York, NY, United States';
var end = 'Lincoln Memorial, Washington, DC, United States';

var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};

dirService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var steps = response.routes[0].legs[0].steps;
createColorPoly(steps);
}
});


}
function createColorPoly(steps){
var path = Array();
for(var step = 0; step < steps.length; step++){
for(var stepP = 0; stepP < steps[step].path.length; stepP++){
path.push(steps[step].path[stepP]);
}
}

var polySelected = {'strokeWeight':'9','strokeColor':'red'};
var polyUnselected = {'strokeWeight':'6','strokeColor':'blue'} ;

var newPoly = new google.maps.Polyline(polyUnselected);
newPoly.setPath(path);
newPoly.setMap(map);
google.maps.event.addListener(newPoly, 'mouseover', function(){newPoly.setOptions(polySelected);});
google.maps.event.addListener(newPoly, 'mouseout', function(){newPoly.setOptions(polyUnselected);});

}
$(document).ready(function(){
initialize();
});

No comments:

Post a Comment