简体   繁体   English

谷歌地图中路线的中点

[英]Midpoint of route in google maps

I was wondering if anyone knew how to use the google maps api to find the midpoint of a route between two places.我想知道是否有人知道如何使用谷歌地图 api 找到两个地方之间路线的中点。 I dont want the geographic center but rather the midpoint along the driving distance.我不想要地理中心,而是想要沿行驶距离的中点。 I am new to both Javascript and the google maps api so if you could include a demo or some code with your answer it would be very helpful.我是 Javascript 和 google maps api 的新手,因此如果您可以在答案中包含演示或一些代码,那将非常有帮助。 The end result would output the latitude and longitude and would represent something like what this website has: http://www.geomidpoint.com/meet/ .最终结果将输出纬度和经度,并表示类似于本网站的内容: http : //www.geomidpoint.com/meet/

So far I have only calculated the geographic midpoint between certain points using the algorithm here: Calculate the center point of multiple latitude/longitude coordinate pairs到目前为止,我只使用这里的算法计算了某些点之间的地理中点: 计算多个纬度/经度坐标对的中心点

I wanted to test efficiencies between geographic center and route midpoint for some research我想测试地理中心和路线中点之间的效率以进行一些研究

Example that calculates the midpoint of a route 计算路线中点的示例

Uses the v3 version of Mike Williams' epoly library.使用 Mike Williams 的epoly库的 v3 版本。

结果地图的屏幕截图

  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  var polyline = null;
  var infowindow = new google.maps.InfoWindow();

function createMarker(latlng, label, html) {
    var contentString = '<b>'+label+'</b><br>'+html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: label,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        marker.myname = label;

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString+"<br>"+marker.getPosition().toUrlValue(6)); 
        infowindow.open(map,marker);
        });
    return marker;
}

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers:true});
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#FF0000',
    strokeWeight: 3
    });
    directionsDisplay.setMap(map);
    calcRoute();
  }
  
  function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var travelMode = google.maps.DirectionsTravelMode.DRIVING

    var request = {
        origin: start,
        destination: end,
        travelMode: travelMode
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        polyline.setPath([]);
        var bounds = new google.maps.LatLngBounds();
        startLocation = new Object();
        endLocation = new Object();
        directionsDisplay.setDirections(response);
        var route = response.routes[0];
        var summaryPanel = document.getElementById("directions_panel");
        summaryPanel.innerHTML = "";

        // For each route, display summary information.
    var path = response.routes[0].overview_path;
    var legs = response.routes[0].legs;
        for (i=0;i<legs.length;i++) {
          if (i == 0) { 
            startLocation.latlng = legs[i].start_location;
            startLocation.address = legs[i].start_address;
            marker = createMarker(legs[i].start_location,"midpoint","","green");
          }
          endLocation.latlng = legs[i].end_location;
          endLocation.address = legs[i].end_address;
          var steps = legs[i].steps;
          for (j=0;j<steps.length;j++) {
            var nextSegment = steps[j].path;
            for (k=0;k<nextSegment.length;k++) {
              polyline.getPath().push(nextSegment[k]);
              bounds.extend(nextSegment[k]);
            }
          }
        }

        polyline.setMap(map);

        computeTotalDistance(response);
      } else {
        alert("directions response "+status);
      }
    });
  }

var totalDist = 0;
var totalTime = 0;
      function computeTotalDistance(result) {
      totalDist = 0;
      totalTime = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        totalDist += myroute.legs[i].distance.value;
        totalTime += myroute.legs[i].duration.value;      
      }
      putMarkerOnRoute(50);

      totalDist = totalDist / 1000.
      document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
      }

      function putMarkerOnRoute(percentage) {
        var distance = (percentage/100) * totalDist;
        var time = ((percentage/100) * totalTime/60).toFixed(2);
        if (!marker) {
          marker = createMarker(polyline.GetPointAtDistance(distance),"time: "+time,"marker");
        } else {
          marker.setPosition(polyline.GetPointAtDistance(distance));
          marker.setTitle("time:"+time);
        }
      }

code snippet:代码片段:

 var directionDisplay; var directionsService = new google.maps.DirectionsService(); var map; var polyline = null; var infowindow = new google.maps.InfoWindow(); function createMarker(latlng, label, html) { var contentString = '<b>' + label + '</b><br>' + html; var marker = new google.maps.Marker({ position: latlng, map: map, title: label, zIndex: Math.round(latlng.lat() * -100000) << 5 }); marker.myname = label; google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString + "<br>" + marker.getPosition().toUrlValue(6)); infowindow.open(map, marker); }); return marker; } function initialize() { directionsDisplay = new google.maps.DirectionsRenderer({ suppressMarkers: true }); var chicago = new google.maps.LatLng(41.850033, -87.6500523); var myOptions = { zoom: 6, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); polyline = new google.maps.Polyline({ path: [], strokeColor: '#FF0000', strokeWeight: 3 }); directionsDisplay.setMap(map); calcRoute(); } function calcRoute() { var start = document.getElementById("start").value; var end = document.getElementById("end").value; var travelMode = google.maps.DirectionsTravelMode.DRIVING var request = { origin: start, destination: end, travelMode: travelMode }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { polyline.setPath([]); var bounds = new google.maps.LatLngBounds(); startLocation = new Object(); endLocation = new Object(); directionsDisplay.setDirections(response); var route = response.routes[0]; var summaryPanel = document.getElementById("directions_panel"); summaryPanel.innerHTML = ""; // For each route, display summary information. var path = response.routes[0].overview_path; var legs = response.routes[0].legs; for (i = 0; i < legs.length; i++) { if (i == 0) { startLocation.latlng = legs[i].start_location; startLocation.address = legs[i].start_address; marker = createMarker(legs[i].start_location, "midpoint", "", "green"); } endLocation.latlng = legs[i].end_location; endLocation.address = legs[i].end_address; var steps = legs[i].steps; for (j = 0; j < steps.length; j++) { var nextSegment = steps[j].path; for (k = 0; k < nextSegment.length; k++) { polyline.getPath().push(nextSegment[k]); bounds.extend(nextSegment[k]); } } } polyline.setMap(map); computeTotalDistance(response); } else { alert("directions response " + status); } }); } var totalDist = 0; var totalTime = 0; function computeTotalDistance(result) { totalDist = 0; totalTime = 0; var myroute = result.routes[0]; for (i = 0; i < myroute.legs.length; i++) { totalDist += myroute.legs[i].distance.value; totalTime += myroute.legs[i].duration.value; } putMarkerOnRoute(50); totalDist = totalDist / 1000. document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes"; } function putMarkerOnRoute(percentage) { var distance = (percentage / 100) * totalDist; var time = ((percentage / 100) * totalTime / 60).toFixed(2); if (!marker) { marker = createMarker(polyline.GetPointAtDistance(distance), "time: " + time, "marker"); } else { marker.setPosition(polyline.GetPointAtDistance(distance)); marker.setTitle("time:" + time); } } google.maps.event.addDomListener(window, 'load', initialize); // from http://www.geocodezip.com/scripts/v3_epoly.js, modified to use the geometry library // === A method which returns a GLatLng of a point a given distance along the path === // === Returns null if the path is shorter than the specified distance === google.maps.Polyline.prototype.GetPointAtDistance = function(metres) { // some awkward special cases if (metres == 0) return this.getPath().getAt(0); if (metres < 0) return null; if (this.getPath().getLength() < 2) return null; var dist = 0; var olddist = 0; for (var i = 1; (i < this.getPath().getLength() && dist < metres); i++) { olddist = dist; dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1)); } if (dist < metres) { return null; } var p1 = this.getPath().getAt(i - 2); var p2 = this.getPath().getAt(i - 1); var m = (metres - olddist) / (dist - olddist); return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m); }
 html { height: 100% } body { height: 100%; margin: 0px; padding: 0px }
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script> <div id="tools"> start: <input type="text" name="start" id="start" value="Hyderabad" /> end: <input type="text" name="end" id="end" value="Bangalore" /> <input type="submit" onclick="calcRoute();" /><br /> </div> <div id="map_canvas" style="float:left;width:70%;height:80%;"></div> <div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px"> <div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div> <div id="total"></div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM