3

I'm doing map application i need to find out the area of the map , min latitude , max latitude , min longitude , max longitude . i did but not sure this is the right way or not i'm confusing here ,

google maps add event listener zoom based i need to get the Area of the map and MIN,MAX (latitude, longitude) , using this value i can find out the correct polygon in DB and showing the correct result of polygons based that area zoom level , MIN,MAX(latitude,longitude) based .

Anyone can suggest this is the right way or i need to change my code

    <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" /> 
varun kumar
  • 101
  • 2
  • 10

2 Answers2

4

You can find area quite easily. Make sure that the map is already loaded before calculating area.

All you need to do is to get the map bounds and then extract (and properly use) the coordinates of the corners.

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

You get north-west and south-east corners from the two above:

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

Now define a function as 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);
    }
}

Using this function calculate the length and breadth of the map and then find the area.

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

Now area,

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

Referred from: get boundaries longitude and latitude from current zoom google maps

HoffZ
  • 7,709
  • 6
  • 36
  • 40
ihimv
  • 1,308
  • 12
  • 25
  • 1
    Should breadth not be as follows in order to get the opposite corner?: `var breadth = getDistanceInMeters(sw, se);` – Malcolm Murray Nov 09 '17 at 16:16
  • I've edited the answer: Fixed error pointed out by @MalcolmMurray. Also corrected calls to non-existing functions.@varun-kumar, you should check that the critical bug is not used on any of your applications... The old code did not return the correct area size. – HoffZ Feb 28 '18 at 10:34
3

An easier way may be to use the built in Google maps functions i.e.

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

Note you must load the "geometry" library as part of googlemaps i.e.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
Chris
  • 26,744
  • 48
  • 193
  • 345