如何使用 google 地图 api 在折线中分配信息 window

How to assign info window in polyline using google map api

我的场景。我有五个标记并连接到折线。当我在折线之间单击标记 a 到标记 b 时,它将显示信息 window。在信息中,window 具有标记 a 地址和标记 b 地址。我在 google 地图 API 中使用 islocationedge 概念实现了这个场景。但这个概念我面临一个问题。当我单击标记 a 到标记 b 折线时,它将显示标记 b 和标记 c 地址,因为我使用了分段折线。我需要如何在单个多段线中分配信息 window。

我的代码

<!DOCTYPE html>
<html>
<body>

<h1>My First Google Map</h1>

<div id="googleMap" style="width:100%;height:400px;"></div>

<script>
function myMap() {
var mapProp= {
  center:new google.maps.LatLng(51.508742,-0.120850),
  zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var goldenGatePosition = [{lat: 30.2179130,lng: -81.5628150, address: 'Tamil Nadu'},{lat: 30.2179140,lng: -81.5627480, address: 'India'},{lat:30.2177650,lng:-81.5629100,address: 'America'},{lat: 30.2844080,lng: -81.5633900, address: 'Tamil Nadu'},{lat: 30.2843840,lng: -81.5633890, address: 'Tamil Nadu'}];
for(let i=0;i<goldenGatePosition.length;i++){
  var marker = new google.maps.Marker({
            position: goldenGatePosition[i],
            map: map,
            title: 'Golden Gate Bridge'
            });
}
var flightPath = new google.maps.Polyline({
  path:goldenGatePosition,
  strokeColor:"#0000FF",
  strokeOpacity:0.8,
  strokeWeight:2
});
flightPath.setMap(map);
let poly, geodesicPoly;
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
      // make polyline for each segment of the input line
      for (var i = 0; i < this.getPath().getLength() - 1; i++) {
        var segmentPolyline = new google.maps.Polyline({
          path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
        });
        console.log(segmentPolyline)
        // check to see if the clicked point is along that segment
        if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
          console.log(' I ', i)
          // output the segment number and endpoints in the InfoWindow
          var origin = new Array()
          var destination = new Array()
          console.log('****************')
            for(let i=0;i<goldenGatePosition.length; i++){
              console.log(goldenGatePosition[i])
            }
            console.log('****************')
          console.log(segmentPolyline.getPath().getAt(0).address)
          origin.push(segmentPolyline.getPath().getAt(0).toUrlValue(6))
          destination.push(segmentPolyline.getPath().getAt(1).toUrlValue(6))
          const service = new google.maps.DistanceMatrixService(); // instantiate Distance Matrix service
      const matrixOptions = {
        origins: origin, // technician locations
        destinations: destination, // customer address
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.IMPERIAL
      };
      // Call Distance Matrix service
      service.getDistanceMatrix(matrixOptions, callback);

      // Callback function used to process Distance Matrix response
      function callback(response, status) {
        console.log(response)
        console.log(status)
        if (status !== "OK") {
          alert("Error with distance matrix");
          return;
        }
        console.log(response);        
      }
          var content = "segment " + i + "<br>";
          content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
          content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
          infowindow.setContent(content);
          infowindow.setPosition(event.latLng);
          infowindow.open(map);
        }
      }
    });
}  
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAiybKuHI544-t5XPZzBGjQOBCO4MZFCwM&callback=myMap&libraries=geometry"></script>

</body>
</html>

当我点击折线时。如何获取折线一端到另一端的标记坐标

您对 isLocationOnEdge 的调用容差太小。

isLocationOnEdge isLocationOnEdge(point, poly[, tolerance])
Parameters:
point: LatLng
poly: Polygon|Polyline
tolerance: number optional
Return Value:* boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.

您的代码:

if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {

工作值:

if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-7)) {

(当它太大时,它会为段 0 上的所有位置选择段 1,据我所知,所有其他段都可以正确使用您的值)

proof of concept fiddle

代码片段:

function myMap() {
  var mapProp = {
    center: new google.maps.LatLng(51.508742, -0.120850),
    zoom: 5,
  };
  var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
  var bounds = new google.maps.LatLngBounds();
  for (let i = 0; i < goldenGatePosition.length; i++) {
    var marker = new google.maps.Marker({
      position: goldenGatePosition[i],
      map: map,
      title: goldenGatePosition[i].address
    });
    if (i == 0 || i == 1) bounds.extend(marker.getPosition());
  }
  map.fitBounds(bounds);
  var flightPath = new google.maps.Polyline({
    path: goldenGatePosition,
    strokeColor: "#0000FF",
    strokeOpacity: 0.8,
    strokeWeight: 2
  });
  flightPath.setMap(map);
  let poly, geodesicPoly;
  var infowindow = new google.maps.InfoWindow();
  var codeStr = ''
  google.maps.event.addListener(flightPath, 'click', function(event) {
    // make polyline for each segment of the input line
    for (var i = 0; i < this.getPath().getLength() - 1; i++) {
      var segmentPolyline = new google.maps.Polyline({
        path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
      });
      console.log(segmentPolyline)
      // check to see if the clicked point is along that segment
      if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-7)) {
        console.log(' I ', i)
        // output the segment number and endpoints in the InfoWindow
        var origin = new Array()
        var destination = new Array()
        console.log('****************')
        for (let i = 0; i < goldenGatePosition.length; i++) {
          console.log(goldenGatePosition[i])
        }
        console.log('****************')
        console.log(segmentPolyline.getPath().getAt(0).address)
        origin.push(segmentPolyline.getPath().getAt(0).toUrlValue(6))
        destination.push(segmentPolyline.getPath().getAt(1).toUrlValue(6))
        const service = new google.maps.DistanceMatrixService(); // instantiate Distance Matrix service
        const matrixOptions = {
          origins: origin, // technician locations
          destinations: destination, // customer address
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.IMPERIAL
        };
        // Call Distance Matrix service
        service.getDistanceMatrix(matrixOptions, callback);
        console.log("break")

        // Callback function used to process Distance Matrix response
        function callback(response, status) {
          console.log(response)
          console.log(status)
          if (status !== "OK") {
            alert("Error with distance matrix");
            return;
          }
          console.log(response);
        }
        var content = "segment " + i + "<br>";
        content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
        content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
        infowindow.setContent(content);
        infowindow.setPosition(event.latLng);
        infowindow.open(map);
      }
    }
  });
}
var goldenGatePosition = [{
  lat: 30.2179130,
  lng: -81.5628150,
  address: 'Tamil Nadu'
}, {
  lat: 30.2179140,
  lng: -81.5627480,
  address: 'India'
}, {
  lat: 30.2177650,
  lng: -81.5629100,
  address: 'America'
}, {
  lat: 30.2844080,
  lng: -81.5633900,
  address: 'Tamil Nadu'
}, {
  lat: 30.2843840,
  lng: -81.5633890,
  address: 'Tamil Nadu'
}];
html,
body,
#googleMap {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
<div id="googleMap"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap&libraries=geometry" defer></script>