如何使用谷歌地图获取折线中的坐标? [英] How to get coordinates in polyline using google map?

查看:66
本文介绍了如何使用谷歌地图获取折线中的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Google Maps中创建一条折线.它已创建,折线也可以正常工作.但是我需要何时单击折线来获取坐标.我的场景(我在Google map.so中有三个标记,用于连接折线的三个标记markerA连接到markerB,连接标记C.当我在markerA和makrerB之间单击折线时,我需要两个标记纬度和经度).如何实现这种情况.

我的代码

 <!DOCTYPE html>< html><身体>< h1>我的第一个Google地图</h1>< div id =" googleMap"style ="width:100%; height:400px;"</div>< script>函数myMap(){var mapProp = {中心:新的google.maps.LatLng(51.508742,-0.120850),变焦: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(让i = 0; i< goldenGatePosition.length; i ++){var marker = new google.maps.Marker({位置:goldenGatePosition [i],地图:标题:金门大桥"});}var flightPath = new google.maps.Polyline({路径:goldenGatePosition,strokeColor:#0000FF",strokeOpacity:0.8,重量: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. 使用

    代码段:

     /*始终明确设置地图高度以定义div的大小*包含地图的元素.*/#谷歌地图 {高度:80%;}/*可选:使示例页面填充窗口.*/html,身体 {高度:100%;边距:0;填充:0;}  

     < h1>我的第一个Google Map</h1>< div id ="googleMap"></div>< script>函数myMap(){var mapProp = {中心:新的google.maps.LatLng(51.508742,-0.120850),变焦:5};var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);var goldenGatePosition = [{拉特:11.0168,lng:76.9558},{经度:11.6643,lng:78.1460},{经度:11.2189,lng:78.1674}];var bounds = new google.maps.LatLngBounds();for(让i = 0; i< goldenGatePosition.length; i ++){var marker = new google.maps.Marker({位置:goldenGatePosition [i],地图:标题:金门大桥"});bounds.extend(goldenGatePosition [i]);}var flightPath = new google.maps.Polyline({路径:goldenGatePosition,strokeColor:#0000FF",strokeOpacity:0.8,重量:2});flightPath.setMap(map);map.fitBounds(bounds);var infowindow = new google.maps.InfoWindow();var codeStr =''google.maps.event.addListener(flightPath,'click',function(event){//为输入线的每个线段制作折线for(var i = 0; i< this.getPath().getLength()-1; i ++){var segmentPolyline = new google.maps.Polyline({路径:[this.getPath().getAt(i),this.getPath().getAt(i + 1)]});//检查点击点是否沿着该线段如果(google.maps.geometry.poly.isLocationOnEdge(event.latLng,segmentPolyline,10e-3)){//在InfoWindow中输出段号和端点var content ="segment" + i +< br>";内容+ =段的开始=" + segmentPolyline.getPath().getAt(0).toUrlValue(6)+< br>";内容+ =段的结尾=" + 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>  

    I tried to create a polyline in google Maps. It's created and polyline also working fine. but I need when to click polyline to get coordinates. My Scenario(I have three markers in google map.so, three markers used to connect the polyline markerA connect to markerB connect to markerC. when I click polyline in between markerA and makrerB. I need that two markers latitude and longitude). How to achieve this scenario.

    My Code

    <!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 Map

    解决方案

    Simplest way:

    1. include the google maps geometry library.
    2. use the poly namespace isLocationOnEdge method to detect which segment of the polyline the click was on. Output the two end coordinates of that segment.

    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

    code snippet:

    /* 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>

    这篇关于如何使用谷歌地图获取折线中的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆