Google Maps | Display routes to different locations from common starting point

| By Webner

Suppose in Google Maps you want to display routes to different locations from common starting

For this we need accurate lat/long of the origin and destination addresses (only 1 origin and multiple destinations). We will use following statement to draw 1 route and run it in a loop while keeping source lat/long same and changing destination lat/long as needed:

my.routes.r = new Route([[source_lat,source_long],[destination_lat,destination_long]]).drawRoute(my.maps.map1);

Here ‘map_canvas’ is the id of the div containing the map.

Here is more detailed explanation:

Suppose I have array of locations in any php variable. The lat long in an array are comma separated like “lat1,long1,lat2,long2,lat3,long3….”. Now to get those in js we will do something like below:

var array1 = '';//$destinations contains value of the form lat1,long1,lat2,long2,lat3,long3
We will split the string on , to get the lat and long.
var finaldestination1 = array1.split(',');
        *  following function draws route on a map
        * @param map object google.maps.Map
        * @return object Route
      Route.prototype.drawRoute = function(map)
        var _this=this;
        {'origin': this.origin,
        'destination': this.destination,
        'waypoints': this.waypoints,
        'travelMode': google.maps.DirectionsTravelMode.DRIVING
         = new google.maps.DirectionsRenderer({ 'draggable':true });
        return _this;

Above function should be used as it is. We can change some of the parameters. Like Travel mode etc. In above example it is set to Driving:

Route.prototype.setGMap = function(map){
/*The above function sets map for directionsRenderer*/

initialize function given below is the function where we will pass the lat long to the google to generate a map for us:

function initialize()
     var myOptions = {
     zoom: 4,
     center: new google.maps.LatLng(44.975918,-93.273079), ***** Here the lat long used are the center point of the map. Like where the focus should be.******
     mapTypeId: google.maps.MapTypeId.ROADMAP
     my.maps.map1 = new google.maps.Map(document.getElementById('map_canvas'),
       if(finaldestination1[0]!= '') // check if array is null
        for (var i = 0,j=1; j<=finaldestination1.length; i+=2,j+=2)
	lattopass = parseFloat(finaldestination1[i]);
        longtopass = parseFloat(finaldestination1[j]);
        my.routes.r = new Route([[44.829261,-93.601617],[lattopass,longtopass]]).drawRoute(my.maps.map1);
	} ***** hard coded lat long are of the source location.
	}my.routes.rx=new Route();
      google.maps.event.addDomListener(window, 'load', initialize);

Leave a Reply

Your email address will not be published. Required fields are marked *