Friday, July 3, 2015

Draw map route b/w two points in php using google map api

Draw Map Route:

Pre-Requirement:- Installed PHP and web server as well JQuery working in your project.

Step 1:- Include <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.17&sensor=false"></script> in your view where you want to show map.

Step 2:- In your controller get the points in between we want to create road map route. Let the vars are $start(exp Delhi=28.6100,77.2300) and $end(exp Mumbai=18.9750,72.8258).

Step 3:-In view include the below script after the file is included

<script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  function initialize(start,end) {
    var latlng = new google.maps.LatLng(start);
    directionsDisplay = new google.maps.DirectionsRenderer();
calcRoute();
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    var marker = new google.maps.Marker({
      position: latlng,
      map: map,
      title:"My location"
    });
  }
  function calcRoute(start,end) {
    var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>

Step 4:- In view take the values in hidden input fields as follows

<input type="hidden" name="start_pt" id="start_pt" value="<?php echo $start; ?>"/>
<input type="hidden" name="end_pt" id="end_pt" value="<?php echo $end; ?>"/>

Step 5:- At the end of the file include the script as follows

    <script>
      window.onload = initialize($('#start_pt').val(),$('#end_pt').val());
    </script>

Step 6:-At the end don't forgot to include the div where you want to show the map with your desired dimentions

<div id="map_canvas" style="width:710px; height:300px"></div>

No comments:

Post a Comment