如何在谷歌地图api中找出该区域

时间:2015-12-24 04:52:24

标签: javascript google-maps google-maps-api-3

我正在做地图应用我需要找出地图的区域,最小纬度,最大纬度,最小经度,最大经度。我做了但不确定这是不是正确的方式,我在这里感到困惑,

谷歌地图添加事件监听器缩放我需要获取地图的面积和MIN,MAX(纬度,经度),使用此值我可以找到DB中的正确多边形并显示基于该多边形的正确结果区域缩放级别,MIN,MAX(纬度,经度)。

任何人都可以建议这是正确的方式,或者我需要更改我的代码

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry,places&sensor=true"></script>
    <script>
    function initialize() {
       alert("ok");
        var mapOptions = {
            zoom: 14,
            center: new google.maps.LatLng(24.4799425,73.0934957),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'),  mapOptions);
        var arr = new Array();
        var polygons = [];
        var bounds = new google.maps.LatLngBounds();
        var coordinates = [];
        var marker = new google.maps.Marker;
        var getBounds;

        // downloadUrl("subdivision-coordinates.php", function(data) {
            //var xmlString = $('#xml_values').val();
            var xmlString ="<subdivisions><subdivision name='Madivala'><coord lat='12.920496072962534' lng='77.6198673248291' id='6' /><coord lat='12.92409332232521' lng='77.62896537780762' id='6' /><coord lat='12.927439554274295' lng='77.6209831237793' id='6' /><coord lat='12.923340413955895' lng='77.61634826660156' id='6' /><coord lat='12.92066338803538' lng='77.61960983276367' id='6' /></subdivision><subdivision name='Sarjapur'><coord lat='12.91706608927013' lng='77.62372970581055' id='7' /><coord lat='12.9158948645401' lng='77.6389217376709' id='7' /><coord lat='12.919659495917085' lng='77.64299869537354' id='7' /><coord lat='12.92409332232521' lng='77.64793395996094' id='7' /><coord lat='12.92480440036714' lng='77.63424396514893' id='7' /><coord lat='12.920998017844783' lng='77.62089729309082' id='7' /></subdivision><subdivision name='Domulur'><coord lat='12.967758119178917' lng='77.63282775878906' id='8' /><coord lat='12.962237705403682' lng='77.65179634094238' id='8' /><coord lat='12.950025446093244' lng='77.64226913452148' id='8' /><coord lat='12.963826927981351' lng='77.6308536529541' id='8' /><coord lat='12.967507193936736' lng='77.63299942016602' id='8' /></subdivision><subdivision name='Indira Nagar'><coord lat='12.982227713276773' lng='77.63505935668945' id='9' /><coord lat='12.985154985380868' lng='77.64518737792969' id='9' /><coord lat='12.965834352522322' lng='77.64904975891113' id='9' /><coord lat='12.965834352522322' lng='77.63694763183594' id='9' /><coord lat='12.982060439543622' lng='77.63497352600098' id='9' /></subdivision><subdivision name='Mariyapan Palya'><coord lat='12.97846402705198' lng='77.54322052001953' id='10' /><coord lat='12.9792167688559' lng='77.56536483764648' id='10' /><coord lat='12.95671716919877' lng='77.56914138793945' id='10' /><coord lat='12.956298941771568' lng='77.54373550415039' id='10' /></subdivision></subdivisions>";
            var xml = xmlParse(xmlString);
            var subdivision = xml.getElementsByTagName("subdivision");
            for (var i = 0; i < subdivision.length; i++) {
                arr = [];
                var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
                //console.log("coordinates="+xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord"));


                for (var j=0; j < coordinates.length; j++) {
                  arr.push(new google.maps.LatLng(
                        parseFloat(coordinates[j].getAttribute("lat")),
                        parseFloat(coordinates[j].getAttribute("lng"))
                  ));

                  var idd=coordinates[j].getAttribute("id");  
                  bounds.extend(arr[arr.length-1]);

                }

                polygons.push(new google.maps.Polygon({
                    id: idd,
                    paths: arr,
                    strokeColor: '#BA55D3',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#DA70D6',
                    fillOpacity: 0.35
                }));
                polygons[polygons.length-1].setMap(map);

                polygons[polygons.length-1].addListener('click', function (event) {
                    //alert(this.id);
                      var service_name=$('input[name="map_service"]:checked').val();
                      $('#add_to_qh').val(this.id);
                      $('#loc_edit_page').attr('href',"locality_service_edit.php?geoId="+this.id+"&service="+service_name);
                      $("#myModal").modal();
                });
                polygons[polygons.length-1].addListener('rightclick', function (event) {

                    console.log("Need to delete the clicked polygon");
                });


            }

      map.fitBounds(bounds);

              google.maps.event.addListener(map, 'idle', function() {
                zoomLevel = map.getZoom();
                  center=map.getCenter();

                  var bounds1 = map.getBounds();

                  var min_lat = bounds1.getSouthWest().lat();
                  var min_lng = bounds1.getSouthWest().lng();

                  var max_lat = bounds1.getNorthEast().lat();
                  var max_lng = bounds1.getNorthEast().lng();

                  var nw = new google.maps.LatLng(min_lat, max_lng);
                  var se = new google.maps.LatLng(max_lat, min_lng);

                  var area22=google.maps.geometry.spherical.computeArea([bounds1.getNorthEast(),se, bounds1.getSouthWest(), nw]);
                  //Area chage meter2 to meter 
                  area22 = area22/1000000;


                  var min_area = area22-((area22*20)/100);
                  var max_area = area22+((area22*20)/100);

                  $('#area').val(area22);

                  $('#min_area').val(min_area);
                  $('#max_area').val(max_area);

                  $('#min_lat').val(min_lat);
                  $('#max_lat').val(max_lat);
                  $('#min_lng').val(min_lng);
                  $('#max_lng').val(max_lng);

                  //console.log("Zoommmmmm   my area="+area+" Min Area="+min_area+ " Max Area="+max_area);
               });


    }

    function xmlParse(str) {
      if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
      }

      if (typeof DOMParser != 'undefined') {
        return (new DOMParser()).parseFromString(str, 'text/xml');
      }

      return createElement('div', null);
    }

    $(function(){
    initialize();
    });

    </script>
    <div id="map-canvas" style="height:620px;" ></div>    
    <input type="text" id="hidden" name="min_area" /> 
    <input type="text" id="hidden" name="max_area" /> 
    Area : <input type="text" id="area" name="area" /> 
    Min Lat : <input type="text" id="min_lat" name="min_lat" /> 
    Max Lat : <input type="text" id="max_lat" name="max_lat" /> 
    Min Lng : <input type="text" id="min_lng" name="min_lng" /> 
    Max Lng : <input type="text" id="max_lng" name="max_lng" /> 

2 个答案:

答案 0 :(得分:2)

您可以很容易地找到该区域。 在计算区域之前,请确保已加载地图。

您需要做的就是获取地图边界,然后提取(并正确使用)角落的坐标。

var bounds = map.getBounds();
var ne = bounds.getNorthEast(); // LatLng of the north-east corner
var sw = bounds.getSouthWest(); // LatLng of the south-west corder

你从上面的两个角落得到了西北角和东南角:

var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());

现在将函数定义为getDistanceInMeters

function getDistanceInMeters(location1, location2) {
    var lat1 = location1.lat();
    var lon1 = location1.lng();

    var lat2 = location2.lat();
    var lon2 = location2.lng();

    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(lat2 - lat1);
    var dLon = deg2rad(lon2 - lon1);
    var a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c; // Distance in km
    return (d * 1000);

    function deg2rad(deg) {
        return deg * (Math.PI / 180);
    }
}

使用此功能计算地图的长度和宽度,然后找到该区域。

var length = getDistanceInMeters(sw, nw);
var breadth = getDistanceInMeters(sw, se);

现在区域,

var area = length * breadth; // in square meters

参考:get boundaries longitude and latitude from current zoom google maps

答案 1 :(得分:1)

一种更简单的方法可能是使用内置的Google地图功能,即

var bounds = map.getBounds();
var ne = bounds.getNorthEast(); 
var sw = bounds.getSouthWest();
var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());

var latLngList: google.maps.LatLng[] = [ne, nw, sw, se];
console.log("Area is", google.maps.geometry.spherical.computeArea(latLngList));

请注意,您必须将“ geometry”库作为googlemaps的一部分加载。

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">