【问题标题】:Google maps api containsLocation always returning false谷歌地图 api containsLocation 总是返回 false
【发布时间】:2020-12-26 14:04:37
【问题描述】:

我用谷歌地图绘制了一个多边形,并试图在多边形中包含一个位置,但 containsLocation 函数总是返回 false。不确定多边形上的点是否必须在完全相同的位置开始和结束,或者我的代码是否存在问题。

我的 containsLocation lat lng 的位置在形状中。


var rightShoulderFront = new google.maps.Polygon({
  paths: outerCoords
});
const map = new google.maps.Map(document.getElementById("mapSect"), {
  center: { lat:3.528319665937775,lng:101.7580347776062 },
  zoom: 5,
});


var outerCoords =[
  {lat:3.528319665937775,lng:101.7580347776062},
  {lat:3.003044444012029,lng:101.4085838669952},
  {lat:2.9951223092598767,lng:101.82611927913445},
  {lat:3.5216453,lng:101.7636108}
]

      geocoder.geocode({address: selectedFullAddress,},function(results,status)
      {
        lat = results[0].geometry.location.lat();
        lng = results[0].geometry.location.lng();
     
        var curPosition     = new google.maps.LatLng(lat,lng);
        var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront)
      });

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    也许以下内容会有所帮助。我稍微重新安排了一些东西,做了一些小的修改,但基本上是一样的。在原版中,您在声明 outerCoords 之前将其作为值调用,所以我想控制台中存在错误。

    <!doctype html>
    <html lang='en'>
        <head>
            <meta charset='utf-8' />
            <title>Google Maps: </title>
            <style>
                #mapSect{
                    width:100%;
                    height:100vh;
                    float:none;
                    margin:auto;
                }
            </style>
            <script>
                function initMap(){
                    // It is unclear where "selectedFullAddress" is defined hence manually assigning here.
                    const selectedFullAddress='Jalan Chengal, Kampung Melayu Subang, 40150 Shah Alam, Selangor, Malaysia';
                    
                    const map = new google.maps.Map( document.getElementById("mapSect"), {
                        center: { lat:3.528319665937775, lng:101.7580347776062 },
                        zoom: 5
                    });
                    
                    const geocoder = new google.maps.Geocoder();
                    
                    // very basic function to add simple marker to aid visualisation
                    const addmarker=function( pos,i ){
                        let marker=new google.maps.Marker({
                            position:pos,
                            title:i + ' [ '+pos+' ]',
                            map:map,
                            draggable:true
                        });
                        return marker;
                    };
                    let bounds=new google.maps.LatLngBounds();
    
                    var outerCoords =[
                        {lat:3.326413,lng:101.258009},
                        {lat:3.388127,lng:101.787869},
                        {lat:2.9951223092598767,lng:101.82611927913445},
                        {lat:3.003044444012029,lng:101.4085838669952},
                        
                    ];
                    var rightShoulderFront = new google.maps.Polygon({
                        paths: outerCoords,
                        strokeColor: '#0000CC',
                        strokeOpacity: 0.5,
                        strokeWeight:1,
                        fillColor:'red',
                        fillOpacity:0.25
                    });
                    
                    // iterate over coordinates and extend the bounds object
                    outerCoords.forEach( (obj,i)=>{
                        bounds.extend(obj);
                    });
                    
                    map.fitBounds( bounds );
                    rightShoulderFront.setMap( map );
                    
                    
                    geocoder.geocode({ address: selectedFullAddress },function(results,status){
                        lat = results[0].geometry.location.lat();
                        lng = results[0].geometry.location.lng();
                        var curPosition     = new google.maps.LatLng(lat,lng);
                        var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront)
                        if( isWithinPolygon ) addmarker( curPosition, 'Found Address: '+isWithinPolygon )
                        console.info(results,isWithinPolygon,status)
                    });
                    
                    
                }
            </script>
            <script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap'></script>
        </head>
        <body>
            <div id='mapSect'></div>
        </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      您对发布的代码有疑问:

      1. JavaScript 错误:InvalidValueError: not an Array 在此行:var rightShoulderFront = new google.maps.Polygon({paths: outerCoords}); 因为尚未定义 outerCoords,并且 null/undefined 不是数组。
      2. JavaScript 错误:Uncaught (in promise) ReferenceError: geocoder is not defined 在此行:geocoder.geocode({address: selectedFullAddress,},function(results,status),因为您的代码中未定义 geocoder
      3. JavaScript 错误:Uncaught (in promise) ReferenceError: selectedFullAddress is not defined,因为您的代码中未定义 selectedFullAddress

      proof of concept fiddle

      代码 sn-p:

      function initMap() {
        var infowindow = new google.maps.InfoWindow();
        var outerCoords = [{
            lat: 3.528319665937775,
            lng: 101.7580347776062
          },
          {
            lat: 3.003044444012029,
            lng: 101.4085838669952
          },
          {
            lat: 2.9951223092598767,
            lng: 101.82611927913445
          },
          {
            lat: 3.5216453,
            lng: 101.7636108
          }
        ]
        const map = new google.maps.Map(document.getElementById("mapSect"));
        var rightShoulderFront = new google.maps.Polygon({
          paths: outerCoords,
          map: map
        });
        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < outerCoords.length; i++) {
          bounds.extend(outerCoords[i]);
        }
        map.fitBounds(bounds);
      
      
        var geocoder = new google.maps.Geocoder();
        var selectedFullAddress = "Kuala Lumpur"
        geocoder.geocode({
          address: selectedFullAddress,
        }, function(results, status) {
          lat = results[0].geometry.location.lat();
          lng = results[0].geometry.location.lng();
          var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map
          })
          var curPosition = new google.maps.LatLng(lat, lng);
          var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront);
          if (isWithinPolygon) {
            infowindow.setContent("isWithinPolygon:" + curPosition.toUrlValue(6));
            infowindow.open(map, marker);
          }
        });
      }
      /* Always set the map height explicitly to define the size of the div
             * element that contains the map. */
      
      #mapSect {
        height: 100%;
      }
      
      
      /* Optional: Makes the sample page fill the window. */
      
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      <!DOCTYPE html>
      <html>
      
      <head>
        <title>Simple Map</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
        <!-- jsFiddle will insert css and js -->
      </head>
      
      <body>
        <div id="mapSect"></div>
      </body>
      
      </html>

      【讨论】:

      • 谢谢你,我的代码不工作的原因是因为没有绘制边界,因此它总是返回 true
      猜你喜欢
      • 2020-08-28
      • 2012-04-10
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多