I'm using one of the example of google map api provided by google. In this example, we can draw some lines on the map using the drawing library.
Lets say I've drawn something. Then how can I share this drawing? or save it for later reference?
Below is the code
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 11,
// only show roadmap type of map, and disable ability to switch to other type
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON, ],
clickable: true,
draggable: true
},
polygonOtions: {
clickable: true,
draggable: true
}
});
drawingManager.setMap(map);
}
Updated:
I'm trying Vadim's solution, but it seems there's a bug. Draw something then refresh you will see
Here's the code that produce the bug:
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
margin: 0;
padding: 0;
height:100%;
}
#map {
height: 100%;
}
.btn {
position:absolute;
width:50px;
height:60px;
top:5%;
left: 50%;
z-index:9999;
color:black;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry,places"></script>
</head>
<body>
<div class="btn" onclick="clearall(map);">delete</div>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 4,
// only show roadmap type of map, and disable ability to switch to other type
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
});
map.data.setControls(['Polygon']);
map.data.setStyle({
editable: true,
draggable: true
});
map.data.addListener('addfeature', savePolygon);
map.data.addListener('removefeature', savePolygon);
map.data.addListener('setgeometry', savePolygon);
//load saved data
loadPolygons(map);
}
function loadPolygons(map) {
var data = JSON.parse(sessionStorage.getItem('geoData'));
// map.data.forEach(function (f) {
// map.data.remove(f);
// });
map.data.addGeoJson(data)
}
function savePolygon() {
map.data.toGeoJson(function (json) {
// console.log(JSON.stringify(json));
sessionStorage.setItem('geoData', JSON.stringify(json));
});
}
function clearall(map){
map.data.forEach(function (f) {
map.data.remove(f);
});
}
initMap();
</script>
</body>
</html>