Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Google Map Javascript API to render a GeoJSON Polygon overlay from JavaScript Variable

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>
like image 295
aruuuuu Avatar asked Jan 09 '23 05:01

aruuuuu


1 Answers

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>
like image 120
geocodezip Avatar answered Jan 26 '23 21:01

geocodezip