Search code examples
google-maps-api-3geojson

addGeoJson Function inverse Lat and Lng?


I'm developing a google map function to display GEOJson Data in a map.

According to the web, the following points are in montreal :

  • Point1 : lat = 45.555 and lng = -73.555
  • Point2 : lat = 45.666 and lng = -73.666

http://www.latlong.net/c/?lat=45.666&long=-73.666

So I've constructed my GEOJson data as follow (displaying two markers in Montreal):

var data_default = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [45.555, -73.555]
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [45.666, -73.666]
            }
        }
    ] };

However, for this data, the following function :

map.data.addGeoJson(data);

Is not indicated the points in Montreal .... to have Montreal I should inverse the latitude and lng of the "coordinates" .. so my two points should have the following coordinates : [-73.555, 45.555 ] [-73.666, 45.666] instead of [45.555, -73.555 ] [45.666,-73.666]

Is any one can explain to me why the addGeoJson of Google maps api is reading the points in an inverse way ?

Thank you


Solution

  • GeoJSON specifies coordinates as [longitude,latitude]. You have the coordinates backwards.

    From the spec:

    Point coordinates are in x, y order (easting, northing for projected coordinates, longitude, latitude for geographic coordinates):

    code snippet:

    function initialize() {
      var map = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(45.555, -73.555),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      var data_default = {
        "type": "FeatureCollection",
        "features": [{
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [-73.555, 45.555]
          }
        }, {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [-73.666, 45.666]
          }
        }]
      };
      map.data.addGeoJson(data_default);
    }
    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"></script>
    <div id="map_canvas"></div>