Google Maps API v3:是否有任何函数可以检查坐标是否在省或国家/地区内

che*_*der 2 javascript google-maps google-maps-api-3

我想允许用户自己介绍坐标。以下代码有效:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

Sud*_*oti 5

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

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
        }
    });
Run Code Online (Sandbox Code Playgroud)