javascript - 谷歌地图 API v3 : is there any function to check if a coordinate is inside a province or country

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

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

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
        }
    });

关于javascript - 谷歌地图 API v3 : is there any function to check if a coordinate is inside a province or country,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679946/

相关文章:

javascript - 浏览器字体中每个字符的渲染像素宽度数据

javascript - 使用 jquery 形成预填充(使其可扩展)

android - 更改默认蓝色位置标记的颜色

ios - 子类化 GMSMarker 和 GMSMapViewDelegate didTapMarker

javascript - 如何使用来自 Google Maps Places API 的结果更新 Angular 范围参数?

javascript - 谷歌地图 : How to prevent InfoWindow from shifting the map

javascript - 如何将 2 个或更多 jquery 函数与执行相同操作但名称不同的元素组合起来

javascript - 测试字符串是否有数字字符的条件

javascript - 根据其标记缩放和居中 Google map (JavaScript API V3)

javascript - 使用 Google map API 的 CSP 不安全评估