Sunday, 21 June 2015

Google map and Direction API with Visualforce page

Google map API : https://developers.google.com/maps/documentation/javascript/tutorial

Google Direction API: https://developers.google.com/maps/documentation/directions/

Demo: http://jsfiddle.net/vc1zwft0/

Same i want to use in salesforce with dynamic addresses.

So This is the code.

Implement same and write some logic in controller side.

<apex:page showHeader="false" >
<head>
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
   <title>Google Maps API v3 Directions Example</title>
   <script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=true"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">

    <div style="width: 100%;" id="mapDiv">
        <div id="map" style="width: 70%; height: 600px; float: left;margin:0px;color:black;"></div>
        <div id="panel" style="width: 30%; float: left;margin:0px;"></div>
    </div>
    <script type="text/javascript">

     var directionsService = new google.maps.DirectionsService();
     var directionsDisplay = new google.maps.DirectionsRenderer();

     var map = new google.maps.Map(document.getElementById('map'), {
               zoom:7,
               mapTypeId: google.maps.MapTypeId.ROADMAP
     });

     directionsDisplay.setMap(map);
     directionsDisplay.setPanel(document.getElementById('panel'));

     var request = {
       origin: 'Mumbai',
       destination: 'Navi Mumbai',
       travelMode: google.maps.DirectionsTravelMode.DRIVING
     };

     directionsService.route(request, function(response, status) {
       if (status == google.maps.DirectionsStatus.OK) {
         directionsDisplay.setDirections(response);
       }
     });
   </script>
</body>
</apex:page>


Here instead of using hard coded value you can create string at controller level and pass here.

origin: {!start address }
destination:- {end address}

Source :- http://stackoverflow.com/questions/3896871/google-map-driving-direction-source-code-for-their-example