2015-09-23 3 views
0

У меня есть карта Google. Когда пользователь нажимает, он помещает маркер «start». Второй клик дает полилинию между первым кликом и вторым кликом и добавляет маркер конца. Третий клик добавляет еще одну точку данных в полилинию и перемещает маркер конца в последний клик. Ничего особенного:Извлечь полилинию с карты Google на GeoJSON

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); 
    } 
} 

Я хотел бы получить нанесенные точки в формате GeoJSON. Я знаю, что Google недавно выпустила слой данных API с вызовом .toGeoJson(), но, естественно, данные пуст, потому что он не был добавлен к слою данных:

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

Таким образом, вопрос, как я могу добавить мои данные - маркеры и полилиния - к слою Data, чтобы я мог получить этот сладкий GeoJSON?

Примечание. Я понимаю, что уровень данных имеет функциональность, которая позволяет пользователям рисовать на карте, но мне нужно сделать это по-своему.

+0

'Uncaught ReferenceError: startMarker не определен' – geocodezip

+0

Извините, не включил весь код, просто хотел дать представление о том, что я делаю. Будет ли полезен весь код? Вам понадобится html тоже, я полагаю, – niborg

+0

Мне не нужен _all_ ваш код просто [Минимальный, полный, проверенный и читаемый пример] (http://stackoverflow.com/help/mcve), который демонстрирует проблему. Приведенная ошибка подразумевает, что он не был протестирован. – geocodezip

ответ

3

Это создаст GeoJSON представляющий полилинию и добавить его к слою данных:

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

фрагмент кода:

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.com/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

Этот подход отлично работает, спасибо. – niborg

Смежные вопросы