如何设置谷歌地图方向服务和距离矩阵javascript api

时间:2018-03-08 11:36:55

标签: javascript php google-maps web

我正在开发一个项目,为公交车绘制一条路线,并在我的html文件中显示它将在div中覆盖的总距离。我的javascript源被导入到包含谷歌地图javascript api的html文件中的问题。下面是我的问题的截图。我的错误来自javascript控制台:

  1. 警告:您已多次添加Google Maps API 这一页。这可能会导致意外错误。

  2. initMap不是一个函数。

  3. 我希望能够在一个div中查看路线详细信息和路径以及公交车到达目的地的距离和预计到达时间。 目前,当我移动 时 在顶部或底部之间,我要么得到地图,要么得到距离计算。 我们将非常感谢您的帮助......

        <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <title>Travel modes in directions</title>
        <style>
          /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
          #map {
            height: 100%;
          }
          /* Optional: Makes the sample page fill the window. */
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
        </style>
    
      </head>
      <body>
        <div id = "view_distance">
          <br>
          Basic example for using the Distance Matrix.<br><br>
          Origin: <input id="orig" type="text" style="width:35em"><br><br>
          Destination: <input id="dest" type="text" style="width:35em"><br><br>
          Distance: <input id="dist" type="text" style="width:35em">
        </div>
        <div id="map"></div>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB9SXvLdo1FnKd8lcuVtvQaSx1tqqE_NFA&callback=initMap">
        </script>
        <script>
          function initMap() {
            var directionsDisplay = new google.maps.DirectionsRenderer;
            var directionsService = new google.maps.DirectionsService;
            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 15,
              center:  {lat: -15.408200, lng: 28.287201}
            });
            directionsDisplay.setMap(map);
    
            DisplayRoute(directionsService, directionsDisplay);
    
    
          }
    
          function DisplayRoute(directionsService, directionsDisplay) {
            directionsService.route({
              origin:  {lat: -15.408200, lng: 28.287201},//Lusaka
              destination: {lat: -17.8419, lng: 25.8543},//Livingstone
              travelMode: 'DRIVING'
            }, function(response, status) {
              if (status == 'OK') {
                directionsDisplay.setDirections(response);
              } else {
                window.alert('Directions request failed due to ' + status);
              }
            });
          }
    
        var origin = new google.maps.LatLng(-15.408200,28.287201),
            destination = {lat: -17.8419, lng: 25.8543},//Livingstone
            service = new google.maps.DistanceMatrixService();
    
        service.getDistanceMatrix(
            {
                origins: [origin],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                avoidHighways: false,
                avoidTolls: false
            },
            callback
        );
    
        function callback(response, status) {
            var orig = document.getElementById("orig"),
                dest = document.getElementById("dest"),
                dist = document.getElementById("dist");
    
            if(status=="OK") {
                orig.value = response.destinationAddresses[0];
                dest.value = response.originAddresses[0];
                //displays the distance
                dist.value = response.rows[0].elements[0].distance.text;
            } else {
                alert("Error: " + status);
            }
        }
        </script>
        <!-- <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB9SXvLdo1FnKd8lcuVtvQaSx1tqqE_NFA&callback=initMap">
        </script> -->
      </body>
    </html>
    

1 个答案:

答案 0 :(得分:0)

    <script>
          
    	           var start = {lat: -15.3875259, lng: 28.3228165};
    	           var end = {lat: -17.86263115, lng: 25.85589126};
    	           var stophere = {lat: -17.3426664, lng: 27.26371218};
    			   var stophere2 = {lat: -17.02884158, lng: 26.48808979};
    			   
    	           var waypts = [{location: stophere,stopover: true},{location: stophere2,stopover: true}];
    	  
                 function initMap()
    	         {
                  var directionsService = new google.maps.DirectionsService;
                  var directionsDisplay = new google.maps.DirectionsRenderer;
                  var map = new google.maps.Map(document.getElementById('map'), 
    		        {
                      zoom: 15,
                      center: start,
    			      mapTypeControl: true,
                      mapTypeId: 'satellite',
    				  rotateControl: true,
                      fullscreenControl: false

                   });
    			   
                 directionsDisplay.setMap(map);
                 calculateAndDisplayRoute(directionsService, directionsDisplay);
    		  
    		     //Center control methods
    		     var centerControlDiv = document.createElement('div');
                 var centerControl = new CenterControl(centerControlDiv, map);
     
                 centerControlDiv.index = 1;
                 map.controls[google.maps.ControlPosition.TOP_RIGHT].push(centerControlDiv);

    		  
    		     //infoWindows begin here
    	         var contentString = '<div id=\"content\">'+
                 '<div id=\"siteNotice\">'+
                 '</div>'+'<h4 id=\"firstHeading\" class=\"firstHeading\">'+'Tap other markers to see information<br/><br/>your STARTING POINT...'+'</h4>'+
                 '<h4 id=\"firstHeading\" class=\"firstHeading\" style=\"color:red;\">10</h4>'+
                 '<div id=\"bodyContent\">'+
                 '<p><b>Fare to Station = ZMW 10 </b><br><b>Inter Station Fare = ZMW 10 </b><br><b>Fare to Destination = ZMW 20 </b><br/><br><b>Total Fare = ZMW 20 </b><br/><b>Distance to next Stop = <span id=\"distanceID\"></span></b></p>'+
                 '</div>'+
                 '</div>';

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

                 var marker = new google.maps.Marker({
                  position: start,
                  map: map,
    		      zIndex: google.maps.Marker.MAX_ZINDEX + 1,
                  title: '".$originVal."'
                  });
    			  
                 marker.addListener('click',function(){infowindow.open(map, marker);});
                 infowindow.open(map, marker);
    		  
    		  
    		     //InfoWindow at intermediate station
    		     //infoWindows begin here
    	         var contentStringStation = '<div id=\"content\">'+
                 '<div id=\"siteNotice\">'+
                 '</div>'+'<h4 id=\"firstHeading\" class=\"firstHeading\">'+'Change bus here...'+'</h4>'+
                 '<h4 id=\"firstHeading\" class=\"firstHeading\" style=\"color:red;\">Kalomo</h4>'+
                 '<div id=\"bodyContent\">'+
                 '<p><b>Fare to next station = ZMW 10 </b></p>'+
                 '</div>'+
                 '</div>';

                 var infowindowStation = new google.maps.InfoWindow({
                 content: contentStringStation,
                 maxWidth: 200
                 });

                 var markerBusStation = new google.maps.Marker({
                 position: stophere,
                 map: map,
    		     zIndex: google.maps.Marker.MAX_ZINDEX + 1,
                 title: '".$staWayptName."'
                 });
    		
                  markerBusStation.addListener('click',function(){infowindowStation.open(map, markerBusStation);});
    		  
    		      
    			  //InfoWindow at intermediate station 2
    		     //infoWindows begin here
    	         var contentStringStation2 = '<div id=\"content\">'+
                 '<div id=\"siteNotice\">'+
                 '</div>'+'<h4 id=\"firstHeading\" class=\"firstHeading\">'+'Change bus here...'+'</h4>'+
                 '<h4 id=\"firstHeading\" class=\"firstHeading\" style=\"color:red;\">Zimba</h4>'+
                 '<div id=\"bodyContent\">'+
                 '<p><b>Fare to Destination = ZMW 20 </b></p>'+
                 '</div>'+
                 '</div>';

                 var infowindowStation2 = new google.maps.InfoWindow({
                 content: contentStringStation2,
                 maxWidth: 200
                 });

                 var markerBusStation2 = new google.maps.Marker({
                 position: stophere2,
                 map: map,
    		     zIndex: google.maps.Marker.MAX_ZINDEX + 1,
                 title: '".$WayPts2_Name."'
                 });
    		
                  markerBusStation2.addListener('click',function(){infowindowStation2.open(map, markerBusStation2);});
    			  
    			  
    		  
    		      //InfoWindow at final destination
    		      //infoWindows begin here
    	          var contentStringDest = '<div id=\"content\">'+
                 '<div id=\"siteNotice\">'+
                 '</div>'+'<h4 id=\"firstHeading\" class=\"firstHeading\">'+'your Final stop'+'</h4>'+
                 '<h4 id=\"firstHeading\" class=\"firstHeading\" style=\"color:red;\">Livingstone</h4>'+
                 '<div id=\"bodyContent\">'+
                 '<p></p>'+
                 '</div>'+
                 '</div>';

                 var infowindowDest = new google.maps.InfoWindow({
                 content: contentStringDest,
                 maxWidth: 200
                 });

                 var markerDest = new google.maps.Marker({
                 position: end,
                 map: map,
    		     zIndex: google.maps.Marker.MAX_ZINDEX + 1,
                 title: '".$destName."'
                 });
              
    		     markerDest.addListener('click',function(){infowindowDest.open(map, markerDest);});
              
    		   
                 }

                 function calculateAndDisplayRoute(directionsService, directionsDisplay) 
    	         {
      
                 directionsService.route({
                 origin: start,
                 destination: end,
                 waypoints: waypts,
                 optimizeWaypoints: true,
                 travelMode: 'DRIVING',
    		  
    		     }, 
    		  
    		     function(response, status) 
    		      {
              
    		      if (status === google.maps.DirectionsStatus.OK) 
    			    {
                      directionsDisplay.setDirections(response);
                      var route = response.routes[0];
                      var summaryPanel = document.getElementById('directions_panel');
                      summaryPanel.innerHTML = '';
    				  var distanceSpan = document.getElementById('distanceID');
                      // For each route, display summary information.
                     for (var i = 0; i < route.legs.length; i++) 
    			        {
                          var routeSegment = i + 1;
                          summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
                          '</b><br>';
                          summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                          summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
    					  summaryPanel.innerHTML += route.legs[i].duration.text + '<br>';

    		              summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
    					  if(i==0)
    					  distanceSpan.innerHTML = route.legs[i].distance.text;
                        }
    					 
    					 
                    } 
    				else 
    				{
                      window.location = \"internetError.php\";
                    }
                     });
                  }
    	  
             
    		     //center control for map
    		 
    	         function CenterControl(controlDiv, map) {

                 // Set CSS for the control border.
                 var controlUI = document.createElement('div');
                 controlUI.style.backgroundColor = '#fff';
                 controlUI.style.border = '2px solid #fff';
                 controlUI.style.borderRadius = '3px';
                 controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
                 controlUI.style.cursor = 'pointer';
                 controlUI.style.marginBottom = '22px';
                 controlUI.style.textAlign = 'center';
                 controlUI.title = 'Click to recenter the map';
                 controlDiv.appendChild(controlUI);

                 // Set CSS for the control interior.
                  var controlText = document.createElement('div');
                  controlText.style.color = 'rgb(25,25,25)';
                  controlText.style.fontFamily = 'calibri';
                  controlText.style.fontSize = '12pt';
                  controlText.style.lineHeight = '38px';
                  controlText.style.paddingLeft = '5px';
                  controlText.style.paddingRight = '5px';
                  controlText.innerHTML = 'Show Start Point';
                  controlUI.appendChild(controlText);

                 // Setup the click event center map to start location
                 controlUI.addEventListener('click', function() {
                 map.setCenter(start);
                 });

                 }
    </script>









     
    <style>
          /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
          #map {
            height: 93%;
    		
    		z-index:1;
          }
    	  
          /* Optional: Makes the  page fill the window. */
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
    	  
    	  /* This only works with JavaScript, 
             if it's not present, don't show loader */
             .no-js #loader { display: none;  }
             .js #loader { display: block; position: absolute; left: 100px; top: 0; }
             .se-pre-con {
    	          position: fixed;
    	          left: 0px;
    	          top: 0px;
    	          width: 100%;
    	          height: 100%;
    	          z-index: 9999;
    	          background: url(images/loader-64x/Preloader_2.gif) center no-repeat #fff;
                }
    		
    	  
        </style>
<html>
    <div class="se-pre-con"></div>
      
      <div style="height: 7%; background-color:#0d70bb;" align="center">
         <a id="displayText" href="javascript:toggle();">
    	 <button style="width: 40%; text-align: center; font-family: calibri; font-weight: lighter; height: relative; background-color: white; border: solid 1px #000000; border-radius: 5px; font-size: 1em; padding: 4px;">Show more Details
    	 </button></a> 
         <a href="android_home.php">
    	 <button style="width: 40%; text-align: center; font-family: calibri; font-weight: lighter; height: relative; background-color: white; border: solid 1px #000000; border-radius: 5px; font-size: 1em; padding: 4px;">Try different route</button></a>
      </div>
      
      <div id="toggleText" style="display: none; float:top; z-index: 100000;">
       <div id='directions_panel'
    	        style='float:top; height: relative; font-family: calibri; text-align:left; padding:5px; background-color:#0d70bb; color: #FFFFFF;
    	        z-index: 10; font-size: 0.8em;'>
    			
    			<br/>
    			
      </div>
    	</div>
    		 
     <div id='map'> 
         
     
     </div>
    <script async defer
    	 src='https://maps.googleapis.com/maps/api/js?key=AIzaSyBwiqodRbtEX-U-b3vXlwahF1QlOMw1fug&callback=initMap'>
    </script>
</html>