Reputation: 221
I am trying to find the area of the polygon. This occurs on the loading of the polygon and will be used in functions. Here is my code :
map.data.forEach(function(feature) {
if (feature.getGeometry().getType() == "Polygon") {
var bounds=[];
feature.getGeometry().forEachLatLng(function(path) {
var temp = new google.maps.LatLng(path.lat,path.lng);
bounds.push(temp);
});
console.log(bounds);
console.log(google.maps.geometry.spherical.computeArea(bounds));
}
});
if the loaded object is a polygon, it makes an array of LatLngs and then it should use the computeArea function. I keep getting a NaN returned from this. I looked at the help docs and compute area takes in an area of latLngs, which is what bounds is.
Bounds displays correctly, so I am not sure why the area is not being calculated.
Upvotes: 0
Views: 3281
Reputation: 161324
The .forEachLatLng
function returns a google.maps.LatLng
. That doesn't have .lat
and .lng
properties (and you don't need to convert it to a google.maps.LatLng
, it already is one), those are functions.
This works for me:
map.data.forEach(function(feature) {
if (feature.getGeometry().getType() == "Polygon") {
var bounds=[];
feature.getGeometry().forEachLatLng(function(path) {
bounds.push(path);
});
console.log(bounds);
console.log(google.maps.geometry.spherical.computeArea(bounds));
}
});
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
zoom: 4,
center: {
lat: -28,
lng: 137
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.data.loadGeoJson(
'https://storage.googleapis.com/mapsdevsite/json/google.json', {},
function(features) {
map.data.forEach(function(feature) {
if (feature.getGeometry().getType() == "Polygon") {
var bounds = [];
var polyBnds = new google.maps.LatLngBounds();
feature.getGeometry().forEachLatLng(function(path) {
bounds.push(path);
polyBnds.extend(path);
});
console.log(bounds);
var area = google.maps.geometry.spherical.computeArea(bounds);
console.log(area);
var iW = new google.maps.InfoWindow({
content: area.toFixed(2) + " sq meters",
position: polyBnds.getCenter()
});
iW.open(map);
}
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Upvotes: 5