Google Maps - Get bounds size

by HoffZ

HTML

<script src="https://cdn.rawgit.com/bjornharrtell/jsts/gh-pages/1.4.0/jsts.min.js"></script>
<script src="https://maps.google.com/maps/api/js?sensor=false&amp;libraries=drawing"></script>
<p>
  Right click on map to get bounds size
</p>
<div id="map">

</div>

CSS

#map {
  width: 500px;
  height: 400px;
}

JavaScript

var mapOptions = {
  zoom: 16,
  center: new google.maps.LatLng(62.1482, 6.0696)
};

var map = new google.maps.Map(document.getElementById("map"), mapOptions);

map.addListener('rightclick', function() {
  alert(getAreaSize(map) + ' square meters')
});




function getAreaSize(map) {
  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());

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

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

  return area;

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