Export geoJSON data from Google Maps

前端 未结 3 541
灰色年华
灰色年华 2021-02-03 14:41

Is there built-in support or any library to export geoJSON data from the google.maps.Data layer or google.maps.Data.Feature or googl

相关标签:
3条回答
  • 2021-02-03 15:10

    A sample-function:

    google.maps.Map.prototype.getGeoJson=function(callback){
      var geo={"type": "FeatureCollection","features": []},
          fx=function(g,t){
    
            var that  =[],
                arr,
                f     = {
                          MultiLineString :'LineString',
                          LineString      :'Point',
                          MultiPolygon    :'Polygon',
                          Polygon         :'LinearRing',
                          LinearRing      :'Point',
                          MultiPoint      :'Point'
                        };
    
            switch(t){
              case 'Point':
                g=(g.get)?g.get():g;
                return([g.lng(),g.lat()]);
                break;
              default:
                arr= g.getArray();
                for(var i=0;i<arr.length;++i){
                  that.push(fx(arr[i],f[t]));
                }
                if( t=='LinearRing' 
                      &&
                    that[0]!==that[that.length-1]){
                  that.push([that[0][0],that[0][1]]);
                }
                return that;
            }
          };
    
      this.data.forEach(function(feature){
       var _feature     = {type:'Feature',properties:{}}
           _id          = feature.getId(),
           _geometry    = feature.getGeometry(),
           _type        =_geometry.getType(),
           _coordinates = fx(_geometry,_type);
    
           _feature.geometry={type:_type,coordinates:_coordinates};
           if(typeof _id==='string'){
            _feature.id=_id;
           }
    
           geo.features.push(_feature);
           feature.forEachProperty(function(v,k){
              _feature.properties[k]=v;
           });
      }); 
      if(typeof callback==='function'){
        callback(geo);
      }     
      return geo;
    }
    

    The function creates an object with the data. You may pass a callback as argument which will be executed with the object as argument.

    Sample-call:

    //map is the google.maps.Map-instance
    map.getGeoJson(function(o){console.log(o)});
    

    Demo: http://jsfiddle.net/doktormolle/5F88D/

    Note: the Demo also stores circles, but circles are not supported in GeoJSON. As a workaround it stores circles as a POINT with a radius-property.

    When a POINT with a radius-property will be loaded into the data-layer the demo hides the marker and creates a circle based on geometry and the radius-property instead.


    <edit>: there is now a built-in method available for geoJSON-export: google.maps.Data.toGeoJson()

    See Save Map Instance outside of Google Maps for an example

    0 讨论(0)
  • 2021-02-03 15:15

    None of these worked for me. I figured out a way to export custom Polygons which may be useful for other shapes as well.

    Here's the key export function:

    function getPathArray(polygon) {
        return polygon.getPath().getArray().map(p => {
            return { lat: p.lat(), lng: p.lng() }
        })
    }
    

    Here's a full example:

    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 5,
            center: { lat: 25.774, lng: -70.190 }, // bermuda triangle
        });
    
        const bermudaTriangle = new google.maps.Polygon({
            paths: [
                { lat: 25.774, lng: -80.190 },
                { lat: 18.466, lng: -66.118 },
                { lat: 32.321, lng: -64.757 },
            ],
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            editable: true,
            draggable: false
        });
        bermudaTriangle.setMap(map);
    
        bermudaTriangle.getPaths().forEach(function (path, index) {
            google.maps.event.addListener(path, 'insert_at', function () {
                var data = getPathArray(bermudaTriangle)
                console.log(JSON.stringify(data))
            })
    
            google.maps.event.addListener(path, 'remove_at', function () {
                var data = getPathArray(bermudaTriangle)
                console.log(JSON.stringify(data))
            })
    
            google.maps.event.addListener(path, 'set_at', function () {
                var data = getPathArray(bermudaTriangle)
                console.log(JSON.stringify(data))
            })
        })
    
        google.maps.event.addListener(bermudaTriangle, 'dragend', function () {
            console.log("dragged")
        })
    }
    
    function getPathArray(polygon) {
        return polygon.getPath().getArray().map(p => {
            return { lat: p.lat(), lng: p.lng() }
        })
    }
    

    Then use the json that gets printed to the console and import it

    bermudaTriangle.setPath(JSON.parse(myJson))
    
    0 讨论(0)
  • 2021-02-03 15:16

    Hi i would like to share what I did to export geojson data from google maps to an html textarea.

    This was my html view

         <article id="article3" style="">
            <div style="margin: 2px 0px 2px 0px;">
                <button onclick= "exportData()">Save</button>
            </div>
            <textarea id="geojson-input" placeholder="..." class="" style="height: 97%; width: 100%"></textarea>
        </article>
    

    This was my javascript

         map.data.toGeoJson(function (data) {
                    document.querySelector('#geojson-input').innerHTML = JSON.stringify(data);
                });
    

    The function togeojson which is a function of map.data class, will get all data from the maps and return on object. To display that object on my textarea, I had to convert that object to a string by using JSON.stringify(data);

    Hopes that will help!

    0 讨论(0)
提交回复
热议问题