最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extract polyline from Google map to GeoJSON - Stack Overflow

programmeradmin2浏览0评论

I have a Google Map. When a user clicks, it places a "start" marker. The second click yields a polyline between the first click and the second click, and adds an "end" marker. The third click adds another data point to the polyline, and moves the "end" marker to the most recent click. Nothing special:

map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: -34.397, lng: 150.644},
            zoom: 13
});
map.addListener('click', insertDataPoint);

polyline = new google.maps.Polyline({
            strokeColor: '#000000',
            strokeOpacity: 0.7,
            strokeWeight: 3
}); 
polyline.setMap(map);

plots = [];

... // Bunch of other code that isn't important

function insertDataPoint(e) {   
    var path = polyline.getPath();
    path.push(e.latLng);

    // Logic to set up marker or circle 
    if (plots.length == 0) {
        // Case: first click
        startMarker.setPosition(e.latLng);
        startMarker.setMap(map);
        plots.push(startMarker);                        

    } else {
        if (plots.length != 1) {
            // Case: we have intermediate points between start and end
            var plot = plots.pop();

            var marker = new google.maps.Marker({
                position: plot.getPosition(),
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    fillColor: '#ffffff',
                    fillOpacity: 0.6,
                    strokeColor: '#ffffff',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    scale: 3
                }
            });
            marker.setMap(map);
            plots.push(marker);
        }
        // Case: add an end marker
        endMarker.setPosition(e.latLng);
        if (plots.length == 1) {
            endMarker.setMap(map);
        }
        plots.push(endMarker);
    }
}

I'd like to get the plotted points in GeoJSON format. I know Google recently released the Data layer API with the .toGeoJson() call, but, naturally, the data is empty because it was not added to the Data layer:

map.data.toGeoJson( function(data) {
    alert(JSON.stringify(data)); // {"type":"FeatureCollections", "features":[]}

So the question is how do I add my data -- the markers and polyline -- to the Data layer so I can get that sweet GeoJSON?

Note -- I understand that the Data layer has functionality that allows users to draw on the map, but I need to do it my way.

I have a Google Map. When a user clicks, it places a "start" marker. The second click yields a polyline between the first click and the second click, and adds an "end" marker. The third click adds another data point to the polyline, and moves the "end" marker to the most recent click. Nothing special:

map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: -34.397, lng: 150.644},
            zoom: 13
});
map.addListener('click', insertDataPoint);

polyline = new google.maps.Polyline({
            strokeColor: '#000000',
            strokeOpacity: 0.7,
            strokeWeight: 3
}); 
polyline.setMap(map);

plots = [];

... // Bunch of other code that isn't important

function insertDataPoint(e) {   
    var path = polyline.getPath();
    path.push(e.latLng);

    // Logic to set up marker or circle 
    if (plots.length == 0) {
        // Case: first click
        startMarker.setPosition(e.latLng);
        startMarker.setMap(map);
        plots.push(startMarker);                        

    } else {
        if (plots.length != 1) {
            // Case: we have intermediate points between start and end
            var plot = plots.pop();

            var marker = new google.maps.Marker({
                position: plot.getPosition(),
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    fillColor: '#ffffff',
                    fillOpacity: 0.6,
                    strokeColor: '#ffffff',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    scale: 3
                }
            });
            marker.setMap(map);
            plots.push(marker);
        }
        // Case: add an end marker
        endMarker.setPosition(e.latLng);
        if (plots.length == 1) {
            endMarker.setMap(map);
        }
        plots.push(endMarker);
    }
}

I'd like to get the plotted points in GeoJSON format. I know Google recently released the Data layer API with the .toGeoJson() call, but, naturally, the data is empty because it was not added to the Data layer:

map.data.toGeoJson( function(data) {
    alert(JSON.stringify(data)); // {"type":"FeatureCollections", "features":[]}

So the question is how do I add my data -- the markers and polyline -- to the Data layer so I can get that sweet GeoJSON?

Note -- I understand that the Data layer has functionality that allows users to draw on the map, but I need to do it my way.

Share Improve this question asked Sep 23, 2015 at 23:42 niborgniborg 4196 silver badges16 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

This will create geoJSON representing the polyline and add it to the data layer:

function exportGeoJson() {
    var geoJson = {
        "type": "FeatureCollection",
            "features": []
    };
    var polylineFeature = {
        "type": "Feature",
            "geometry": {
            "type": "LineString",
                "coordinates": []
        },
            "properties": {}
    };
    for (var i = 0; i < polyline.getPath().getLength(); i++) {
        var pt = polyline.getPath().getAt(i);
        polylineFeature.geometry.coordinates.push([
        pt.lng(), pt.lat()]);
    }
    geoJson.features.push(polylineFeature);
    document.getElementById('geojson').value = JSON.stringify(geoJson);
    polyline.setPath([]);
    map.data.addGeoJson(geoJson);
    // Set the stroke width, and fill color for each polygon
    map.data.setStyle({
        strokeColor: 'green',
        strokeWeight: 2
    });
    map.data.toGeoJson( function(data) {
      document.getElementById('exported').value=JSON.stringify(data)
    });

}

proof of concept fiddle

code snippet:

var polyline, map;

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 13
  });
  map.addListener('click', insertDataPoint);

  polyline = new google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 0.7,
    strokeWeight: 3
  });
  polyline.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
plots = [];

// Bunch of other code that isn't important

function insertDataPoint(e) {
  var path = polyline.getPath();
  path.push(e.latLng);

  // Logic to set up marker or circle 
  if (plots.length == 0) {
    // Case: first click
    startMarker.setPosition(e.latLng);
    startMarker.setMap(map);
    plots.push(startMarker);

  } else {
    if (plots.length != 1) {
      // Case: we have intermediate points between start and end
      var plot = plots.pop();

      var marker = new google.maps.Marker({
        position: plot.getPosition(),
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          fillColor: '#ffffff',
          fillOpacity: 0.6,
          strokeColor: '#ffffff',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          scale: 3
        }
      });
      marker.setMap(map);
      plots.push(marker);
    }
    // Case: add an end marker
    endMarker.setPosition(e.latLng);
    if (plots.length == 1) {
      endMarker.setMap(map);
    }
    plots.push(endMarker);
  }
}

function exportGeoJson() {
  var geoJson = {
    "type": "FeatureCollection",
    "features": []
  };
  var polylineFeature = {
    "type": "Feature",
    "geometry": {
      "type": "LineString",
      "coordinates": []
    },
    "properties": {}
  };
  for (var i = 0; i < polyline.getPath().getLength(); i++) {
    var pt = polyline.getPath().getAt(i);
    polylineFeature.geometry.coordinates.push([
      pt.lng(), pt.lat()
    ]);
  }
  geoJson.features.push(polylineFeature);
  document.getElementById('geojson').value = JSON.stringify(geoJson);
  polyline.setPath([]);
  map.data.addGeoJson(geoJson);
  // Set the stroke width, and fill color for each polygon
  map.data.setStyle({
    strokeColor: 'green',
    strokeWeight: 2
  });
  map.data.toGeoJson(function(data) {
    document.getElementById('exported').value = JSON.stringify(data)
  });

}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis./maps/api/js?"></script>
<input type="button" onclick="exportGeoJson()" value="export GeoJson" />
<div id="map" style="border: 2px solid #3872ac;"></div>
<textarea id="geojson" rows="10" cols="70"></textarea>
<br><b>Exported</b>
<br>
<textarea id="exported" rows="10" cols="70"></textarea>

发布评论

评论列表(0)

  1. 暂无评论