Search code examples
google-mapspromisepolygonopenstreetmapgeojson

Create Polygon on Google Maps with JSON of openstreetmap. InvalidValueError: not an Array


I want to show the border between provinces in google maps. In forums it is said that the only way is to call openstreetmap to obtain coordinates, and then create a polygon in Google maps. The code fails, don´t show Polygon and give "InvalidValueError: not an Array". Is it because of the promise call? or because, I do not generate the array well?

    function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), {
      // TNF
          zoom: 10,
          center: {lat: 28.4125202, lng: -16.5566306}, 
          mapTypeId: 'roadmap'
    });
            
            
    var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json'); 

    promise.then(function(data){
        var cachedGeoJson = data; //save the geojson in case we want to update its values
        
        console.log(JSON.stringify(cachedGeoJson));  //OUTPUT-1
        console.log(cachedGeoJson.geometry.coordinates); // OUTPUT-2

        
        for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
                var coord = cachedGeoJson.geometry.coordinates[i];
                coord_poligon.push(coord); 
        };
        
        coord_poligon_JSON = JSON.stringify(coord_poligon); 
        console.log(coord_poligon_JSON );  // OUTPUT-3: 

            
        var geoObject = cachedGeoJson.geometry.coordinates;
        var features = [];
        features = geoObject;
        
        var geoJson = {
            "type": "FeatureCollection",
            "features": [{
              "type": "Feature",
              "geometry": {
                "type": "Polygon",
                "coordinates":features,
              },
              "properties": {}
            }]
        };

        console.log(JSON.stringify(geoJson)); // OUTPUT-4

        
    }); // end promise. 

    // Construct the polygon.
    triangleCoords = geoJson;  

    var bermudaTriangle = new google.maps.Polygon({ 
      paths: triangleCoords, 
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 3,
      fillColor: '#ea0e0e', // red color  
      fillOpacity: 0.20
    });
    bermudaTriangle.setMap(map);


    //OUTPUT-1:
    //{"place_id":256937694,...
    //{"type":"Point","coordinates":[-16.5532956,28.4159024]},"geometry":{"type":"Polygon","coordinates":[[[-16.5705013,28.4080941],[-16.5703805,28.4076554],...

    // OUTPUT-2:    
                //0: (2) [-16.5705013, 28.4080941]
                //1: (2) [-16.5703805, 28.4076554]
                //2: (2) [-16.5701851, 28.4064929]

    // OUTPUT-3: [[[-16.5705013,28.4080941],[-16.5703805,28.4076554],[-16.5701851,28.4064929],...

    // OUTPUT-4: {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-16.5705013,28.4080941],[-16.5703805,28.4076554],

Solution

  • Finally I used the Polygon array, not geoJson. About that: openstreetmap return (lng,lat). It is the reverse order that the Google Maps API needs to create POLYGON, that uses it (lat,lng) so:

    1-STEP: you have to change the coordinate pair order, that´s create a new array with coordenate pairs (lat,lng):

    '''

        var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json'); 
    
        promise.then(function(data){
        
            var cachedGeoJson = data; 
                                
            for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
                        
                var lnglat = cachedGeoJson.geometry.coordinates[i];
                for(var j = 0; j < lnglat.length; j++)
                {
                    
                var longitud = lnglat[j][0]; // first value on openstreetmap is lng
                var latitud = lnglat[j][1]; // second value is lat
                coord_poligon.push(new google.maps.LatLng(parseFloat(latitud), parseFloat(longitud )));
                
                    
                }
            };
    

    ''' 2-STEP: to assign this new array (lat,lng) to array that will create the POLYGON:

    '''

            var triangleCoords = [coord_poligon]; //array inside brackets. IMPORTANT!
                            
            var bermudaTriangle = new google.maps.Polygon({ 
              paths: triangleCoords, // array 
              strokeColor: '#0a6df0', // azul oscuro
              strokeOpacity: 0.8,
              strokeWeight: 3,
              fillColor: '#48cef7', // azul claro 
              fillOpacity: 0.20
            });
            bermudaTriangle.setMap(map);
    
        
            infoWindow = new google.maps.InfoWindow;
    
    
        }); // end promise. 
    

    '''

    COMPLETE CODE:

    '''

    var coord_poligon = [];         
    var triangleCoords = [];
        
        
    function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: {lat: 28.4125202, lng: -16.5566306},   // TNF
          mapTypeId: 'roadmap'
    });
        
        var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json'); 
    
        promise.then(function(data){
        
            var cachedGeoJson = data; 
                    
            for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
                        
                var lnglat = cachedGeoJson.geometry.coordinates[i];
                for(var j = 0; j < lnglat.length; j++)
                {
                    
                var longitud = lnglat[j][0]; // first value on opentreet is  lng
                var latitud = lnglat[j][1]; // second value is lat
                coord_poligon.push(new google.maps.LatLng(parseFloat(latitud), parseFloat(longitud )));
                
                    
                }
            };
            
            var triangleCoords = [coord_poligon]; // array dentro de corchetes . IMPORTANT!
    
            
            var bermudaTriangle = new google.maps.Polygon({ 
              paths: triangleCoords, // array 
              strokeColor: '#0a6df0', // dark blue
              strokeOpacity: 0.8,
              strokeWeight: 3,
              fillColor: '#48cef7', // blue 
              fillOpacity: 0.20
            });
            bermudaTriangle.setMap(map);
    
    
            infoWindow = new google.maps.InfoWindow;
    
    
        }); // end promise. 
        
    } // end initMap()
        
    

    '''