如何使用 google 地图获取折线中的坐标?

How to get coordinates in polyline using google map?

我试图在 google 地图中创建折线。它已创建并且折线也可以正常工作。但我需要什么时候点击多段线来获取坐标。我的场景(我在 google map.so 中有三个标记,三个标记用于连接折线 markerA 连接到 markerB 连接到 markerC。当我单击 markerA 和 makrerB 之间的折线时。我需要两个标记纬度和经度)。如何实现这个场景。

我的代码

<!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: 11.0168,lng: 76.9558},{lat: 11.6643,lng: 78.1460},{lat:11.2189,lng:78.1674}];
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);
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
  infowindow.setContent("content");
//         var pathArr = flightPath.getPath()
//         for (var i = 0; i < pathArr.length; i++){
//     codeStr = '{lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
//     console.log(codeStr)
  

// };
console.log(event.latLng)
var length = this.getLength();
                                        var mid = Math.round( length / 2 );
                                        var pos = this.getAt( mid );
console.log(pos)
        // infowindow.position = event.latLng;
        infowindow.setPosition(event.latLng);
        infowindow.open(map);
    });
}  
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCHmYOxkvd4u3rbHqalUSlGOa-b173lygA&callback=myMap"></script>

</body>
</html>

Google地图

最简单的方法:

  1. 包括 google 地图几何库。
  2. 使用 poly namespace 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.

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)]
    });
    // check to see if the clicked point is along that segment
    if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline,10e-3)) {
      // output the segment number and endpoints in the InfoWindow
      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);
    }
  }
});

proof of concept fiddle

代码片段:

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#googleMap {
  height: 80%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<h1>My First Google Map</h1>

<div id="googleMap"></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: 11.0168,
      lng: 76.9558
    }, {
      lat: 11.6643,
      lng: 78.1460
    }, {
      lat: 11.2189,
      lng: 78.1674
    }];
    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: 'Golden Gate Bridge'
      });
      bounds.extend(goldenGatePosition[i]);
    }
    var flightPath = new google.maps.Polyline({
      path: goldenGatePosition,
      strokeColor: "#0000FF",
      strokeOpacity: 0.8,
      strokeWeight: 2
    });
    flightPath.setMap(map);
    map.fitBounds(bounds);

    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)]
        });
        // check to see if the clicked point is along that segment
        if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
          // output the segment number and endpoints in the InfoWindow
          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=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap"></script>