1

我想让用户自己(或她自己)介绍坐标。以下代码有效:

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

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

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

2 回答 2

4

作为一个选项,您可以进行反向地理编码,例如获取地址融合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
        }
    });
于 2013-09-08T09:06:35.257 回答
3

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

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

于 2013-09-08T18:10:38.933 回答