Drawing routes between markers using Google map API

1.5k views Asked by At

I want to draw a routes between every two points in map using Google map API.

drawing routes using Google map API

3

There are 3 answers

0
Ghaly Saqqal On BEST ANSWER

this my full answer about all my questions in this question :

<div class="paths">

            <a class="path" style="border-left: 6px solid #000000;" 
        href="#" onclick="javascript:reset();javascript:calcRoute($(this).attr('start'), $(this).attr('end'), $(this).attr('color'), $(this).attr('ide'))" 
        start="24.468498279212913,39.615068435668945" 
        end="24.45985083570312,39.66432183980942" 
        color="#000000" 
        ide="5"
        >

        Alkhaldia/King abdulaziz road        </a>
            <a class="path" style="border-left: 6px solid #ff0000;" 
        href="#" onclick="javascript:reset();javascript:calcRoute($(this).attr('start'), $(this).attr('end'), $(this).attr('color'), $(this).attr('ide'))" 
        start="24.471681716990837,39.61108535528183" 
        end="24.501539614912353,39.61090564727783" 
        color="#ff0000" 
        ide="6"
        >

        Saied Al Shuhada        </a>
            <a class="path" style="border-left: 6px solid #00b1ff;" 
        href="#" onclick="javascript:reset();javascript:calcRoute($(this).attr('start'), $(this).attr('end'), $(this).attr('color'), $(this).attr('ide'))" 
        start="24.46727273186149,39.606807231903076" 
        end="24.462189756758278,39.545153975486755" 
        color="#00b1ff" 
        ide="7"
        >

        Sport City        </a>
            <a class="path" style="border-left: 6px solid #ffa900;" 
        href="#" onclick="javascript:reset();javascript:calcRoute($(this).attr('start'), $(this).attr('end'), $(this).attr('color'), $(this).attr('ide'))" 
        start="24.467270,39.606753" 
        end="24.422826,39.520943" 
        color="#ffa900" 
        ide="8"
        >

        Al duaitha        </a>
            <a class="path" style="border-left: 6px solid #41ff00;" 
        href="#" onclick="javascript:reset();javascript:calcRoute($(this).attr('start'), $(this).attr('end'), $(this).attr('color'), $(this).attr('ide'))" 
        start="24.46727273186149,39.606807231903076" 
        end="24.41422098604895,39.62093710899353" 
        color="#41ff00" 
        ide="9"
        >

        Alia Mall        </a>


            <select style="display: none;" id="points_5">
        <option value="24.459040260025855,39.65409994125366"></option><option value="24.47105675396141,39.64922904968262"></option>        </select>
            <select style="display: none;" id="points_6">
                </select>
            <select style="display: none;" id="points_7">
        <option value="24.472355501781344,39.54960644245148"></option>        </select>
            <select style="display: none;" id="points_8">
        <option value="24.420433,39.530202"></option><option value="24.472325,39.549333"></option>        </select>
            <select style="display: none;" id="points_9">
                </select>

</div>

<div class="map_fullscreen" id="map_canvas"></div>

<script type="text/javascript">        
        var markers = [
                            [24.46727273186149,39.606807231903076, 'Al salam Stop', '1'],
                            [24.422826,39.520943, 'ALduaytha Station', '2'],
                            [24.462189756758278,39.545153975486755, 'Prince Mohammed Spor City Station', '2'],
                            [24.468498279212913,39.615068435668945, 'Al Baqee Stop', '1'],
                            [24.467275173202733,39.6067750453949, 'Al salam Stop', '1'],
                            [24.467270,39.606753, 'Al salam Stop', '1'],
                            [24.41422098604895,39.62093710899353, 'Alia Mall Station', '2'],
                            [24.472316441891955,39.54898953437805, 'Turn Left', '0'],
                            [24.420433,39.530202, 'Turn Left', '0'],
                            [24.46727273186149,39.606807231903076, 'Al salam Stop', '1'],
                            [24.46953339357955,39.63470220565796, 'Turn Left', '0'],
                            [24.472355501781344,39.54960644245148, 'Turn Right', '0'],
                            [24.47195513734061,39.548882246017456, 'Turn Left', '0'],
                            [24.421215736553147,39.5303213596344, 'Turn Right', '0'],
                            [24.462189756758278,39.545153975486755, 'Prince Mohammed Spor City Station', '2'],
                            [24.46727273186149,39.606807231903076, 'Al salam Stop', '1'],
                            [24.472325,39.549333, 'Al Salam Road', '0'],
                            [24.458810758735982,39.65430110692978, 'Turn left', '0'],
                            [24.467270,39.606753, 'Al salam Stop', '1'],
                            [24.45985083570312,39.66432183980942, 'Al Khaledia Station', '2'],
                            [24.422826,39.520943, 'ALduaytha Station', '2'],
                            [24.501539614912353,39.61090564727783, 'Saied Alshuhada station', '2'],
                            [24.471681716990837,39.61108535528183, 'Saied Alshuhada', '1'],
                            [24.45985083570312,39.66432183980942, 'Al Khaledia Station', '2'],
                            [24.459040260025855,39.65409994125366, 'Prince MOhammed ben Abdulaziz', '0'],
                            [24.47105675396141,39.64922904968262, 'Turn left', '0'],
                            [24.471681716990837,39.61108535528183, 'Saied Alshuhada Stop', '1'],
                            [24.468498279212913,39.615068435668945, 'Al Baqee Stop', '1'],
                            [24.501539614912353,39.61090564727783, 'Saied Alshuhada Station', '2'],

        ];            

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

        function initialize() {

            // Try HTML5 geolocation
          if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
              var pos = new google.maps.LatLng(position.coords.latitude,
                                               position.coords.longitude);

              var infowindow = new google.maps.InfoWindow({
                map: map,
                position: pos,
                content: 'You Are Here !'
              });

              map.setCenter(pos);
            }, function() {
              handleNoGeolocation(true);
            });
          } else {
            // Browser doesn't support Geolocation
            handleNoGeolocation(false);
          }

            var mapOptions = {

                center: new google.maps.LatLng(24.4676711,39.610379),
                zoom: 15,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                streetViewControl: false,
                mapTypeControl: true,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                    position: google.maps.ControlPosition.BOTTOM_CENTER
                },
                zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.LARGE,
                    position: google.maps.ControlPosition.LEFT_BOTTOM
                },
                disableDefaultUI: true,
                scaleControl: true,
                styles: [{featureType: "landscape", stylers: [{saturation: -100}, {lightness: 65}, {visibility: "on"}]}, {featureType: "poi", stylers: [{saturation: -100}, {lightness: 51}, {visibility: "simplified"}]}, {featureType: "road.highway", stylers: [{saturation: -100}, {visibility: "simplified"}]}, {featureType: "road.arterial", stylers: [{saturation: -100}, {lightness: 30}, {visibility: "on"}]}, {featureType: "road.local", stylers: [{saturation: -100}, {lightness: 40}, {visibility: "on"}]}, {featureType: "transit", stylers: [{saturation: -100}, {visibility: "simplified"}]}, {featureType: "administrative.province", stylers: [{visibility: "off"}]/**/}, {featureType: "administrative.locality", stylers: [{visibility: "off"}]}, {featureType: "administrative.neighborhood", stylers: [{visibility: "on"}]/**/}, {featureType: "water", elementType: "labels", stylers: [{visibility: "on"}, {lightness: -25}, {saturation: -100}]}, {featureType: "water", elementType: "geometry", stylers: [{hue: "#ffff00"}, {lightness: -25}, {saturation: -97}]}]
            };
            map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

            var infowindow = new google.maps.InfoWindow({
              maxWidth: 500,
            });

            var marker;

            var bounds = new google.maps.LatLngBounds();

            for (var i = 0; i < markers.length; ++i) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(markers[i][0], markers[i][1]),
                    map: map,
                    title:markers[i][2],
                    icon: 'images/'+markers[i][3]+'_icn.png' ,
                    optimized: false
                });

                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                      infowindow.setContent(markers[i][2]);
                      infowindow.open(map, marker);
                    }
                  })(marker, i));

                  bounds.extend(new google.maps.LatLng(markers[i][0], markers[i][1]));
            }
            map.fitBounds(bounds);


        }

        function handleNoGeolocation(errorFlag) {
          if (errorFlag) {
            var content = 'Error: The Geolocation service failed.';
          } else {
            var content = 'Error: Your browser doesn\'t support geolocation.';
          }

          var options = {
            map: map,
            position: new google.maps.LatLng(60, 105),
            content: content
          };

          var infowindow = new google.maps.InfoWindow(options);
          map.setCenter(options.position);
        }

        function calcRoute(ss, ee, color, ide) {

            rendererOptions = {
             suppressMarkers : true,
             polylineOptions: {
              strokeColor: color
            }
          };

          directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

          var start = ee.toString();
          var end = ss.toString();
          var waypts = [];
            var checkboxArray = document.getElementById('points_'+ide);

            for (var i = 0; i < checkboxArray.length; i++) {
              waypts.push({
                  location:checkboxArray[i].value,
                  stopover:true});

            }

          var request = {
              origin:start,
              destination:end,
              waypoints: waypts,
              optimizeWaypoints: true,
              travelMode: google.maps.TravelMode.DRIVING
          };

          directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
              directionsDisplay.setDirections(response);

                directionsDisplay.setMap(map);

            }
          });
        }

        google.maps.event.addDomListener(window, 'load', initialize);


      function clearWaypoints() {

        origin = null;
        destination = null;
        waypoints = [];
        directionsVisible = false;
      }

        function reset() {
            clearWaypoints();
            directionsDisplay.setMap(null);
            directionsDisplay.setPanel(null);
            directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));    
          }
    </script>
5
Alp On
  var polylineOptions = {
                        strokeColor: routeColor,
                        strokeOpacity: 0.5,
                        strokeWeight: 8
                    };

 var rendererOptions = {
                        draggable: false,
                        polylineOptions: polylineOptions,
                        suppressMarkers: true,
                        preserveViewport: true
                    };

routePoly = new google.maps.Polyline(polylineOptions);
routeRenderer = new google.maps.DirectionsRenderer(rendererOptions);


routePoly.setPath(new Array());
var polyPath = routePoly.getPath();

for (var i = 0; i< coordinates.length ; i++){
    polyPath.push(coordinates.latLng);
}

 routePoly.setMap(map);

___UPDATE___

You asked for the HTML. The thing is HTML is dynamic. I will post the initial version. I have bunch of other divs there but they are NOT important for your case. (I know this is bare bone of my HTML but it dynamically generated depending on user actions). Regardless, The only div that matters for your is map-canvas. Google Map requires this div to be present and draws MAP and other fancy stuff there.

<!doctype html>
<html lang="en">
<body>

<div id="wholeBody">
     <div id="map-canvas">
     </div>
</div>

</body>
</html>
1
ScaisEdge On

If you just want to draw lines according to a set of points (coordinates) you can use the simple set polylines as in this example but if you want to get the road routes that connect the two points you have to delve into the service google maps directions Here a link introductory