谷歌地图API v3:是否有任何功能可以检查坐标是否在省或国家/地区内

Google Maps API v3: is there any function to check if a coordinate is inside a province or country

本文关键字:是否 坐标 国家 地区 检查 v3 API 任何 功能 谷歌地图      更新时间:2023-09-26

我想允许用户自己(或她自己)引入坐标。以下代码有效:

<head>
    <script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" type="text/javascript"></script>
    <script type="text/javascript" >
    var geocoder;
    var map;
    function paintCoordsInMap() {
      geocoder = new google.maps.Geocoder();
      var lat = document.getElementById('lat').value;
      var lng = document.getElementById('lng').value;
      var latlng = new google.maps.LatLng(lat, lng);
      var mapOptions = {
        zoom: 15,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    }
    </script>
    (...)
</head>

<body>
    (...)
    <f:field bean="alojamientoInstance" property="lat"/>
    <f:field bean="alojamientoInstance" property="lng"/>
    <button type='button' class="btn btn-primary" onclick="paintCoordsInMap()"> find coordinates in map! </button>  
    (...)
</body>

我想检查坐标是否在省(或国家/地区)内,如果没有,则启动窗口警报。如果没有,我将在地图上绘制一个包含省(或国家)的正方形,复制角的坐标。像下面这样的代码应该可以工作(或多或少):

if (lat > 10.111 || lat < 30.1213 || lng < 40.234 || lat > 60.23423) {
    alert('it is outside the country/province!');
}

作为一种选择,您可以进行反向地理编码,例如获取融合latlng的地址,并检查地址是否与您提到的省份匹配,例如:

var geocoder = new google.maps.Geocoder(),
    latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {                
                //get the required address & check
                console.log(results[1].formatted_address); 
            }
        } else {
            //failed
        }
    });

如果您有要检查的省或国家的边界坐标,您可以使用google.maps.geometry.poly.containsLocation方法来确定输入的坐标是否在多边形内。

包含位置(点:LatLng, 多边形:多边形) | 布尔值 |计算给定点是否位于指定的多边形内。