I am trying to render a GeoJSON polygon from a variable called data using the Google Javascript API. The overlay does not render properly and I do not know why. Can somebody please show me how to render a polygon on the map?
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var x=new google.maps.LatLng(40.75597,-73.974228);
function initialize() {
var data = { "type" : "Polygon", "coordinates" : [ [ [ -73.974228, 40.75597 ], [ -73.983841, 40.742931 ], [ -74.008133, 40.75307500000001 ], [ -73.998131, 40.765915 ], [ -73.974228, 40.75597 ] ] ] }
var mapProp = {
center:x,
zoom:4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
map.data.loadGeoJson(data);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
I get a javascript error with your code: Uncaught InvalidValueError: not a Feature or FeatureCollection
. Make your polygon a "Feature":
var data = {
type: "Feature",
geometry: {
"type": "Polygon",
"coordinates": [
[
[-73.974228, 40.75597],
[-73.983841, 40.742931],
[-74.008133, 40.75307500000001],
[-73.998131, 40.765915],
[-73.974228, 40.75597]
]
]
}
};
working fiddle
code snippet:
function initialize() {
var data = {
type: "Feature",
geometry: {
"type": "Polygon",
"coordinates": [
[
[-73.974228, 40.75597],
[-73.983841, 40.742931],
[-74.008133, 40.75307500000001],
[-73.998131, 40.765915],
[-73.974228, 40.75597]
]
]
}
};
var mapProp = {
center: new google.maps.LatLng(40.75597, -73.974228),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
map.data.addGeoJson(data);
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #googleMap {
width: 100%;
height: 100%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="googleMap"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With