1

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>  
angry kiwi
  • 10,730
  • 26
  • 115
  • 161
  • There is a `polygoncomplete` event https://developers.google.com/maps/documentation/javascript/3.exp/reference#DrawingManager you should be able to get your polygon path and save this data for future use. – MrUpsidown Sep 23 '15 at 16:33
  • @MrUpsidown how to get the polygon path? and how to reinstate it ? – angry kiwi Sep 23 '15 at 18:51

2 Answers2

4

You could utilize Google Maps Data layer for that purpose. The below example demonstrates how to export and import polygons as GeoJSON data using google.maps.Data class. localStorage is used for storing GeoJSON data.

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
    });
    bindDataLayerListeners(map.data);

    //load saved data
    loadPolygons(map);
}


// Apply listeners to refresh the GeoJson display on a given data layer.
function bindDataLayerListeners(dataLayer) {
    dataLayer.addListener('addfeature', savePolygon);
    dataLayer.addListener('removefeature', savePolygon);
    dataLayer.addListener('setgeometry', savePolygon);
}

function loadPolygons(map) {
    var data = JSON.parse(localStorage.getItem('geoData'));
    map.data.forEach(function (f) {
        map.data.remove(f);
    });
    map.data.addGeoJson(data)
}



function savePolygon() {
    map.data.toGeoJson(function (json) {
        localStorage.setItem('geoData', JSON.stringify(json));
    });
}

Demo

Update

The following demo demonstrates how to delete polygons.

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • Sure, since currently the data is saved/loaded in localStorage, `savePolygon` and `loadPolygons` need to be modified for that matter – Vadim Gremyachev Sep 25 '15 at 09:34
  • I'm not sure I get what you mean. To reproduce the polygon we need some kind of cornate right? So first we have to extract the polygon's cornate from the map and save to mysql database. Am i right? if so how to do that? – angry kiwi Sep 25 '15 at 09:39
  • 1
    oh. I got it. We can just save the entire json string to database. and use it to reload the object which the polygon in this case – angry kiwi Sep 25 '15 at 10:09
  • And one more thing, your example works fine but it also got error when refresh. To reproduce, draw a polygon, then refresh the browser. You will see the error in firebug console. Sometime you might have to try the procedure a few time to trigger the error. That's weird, but that's how I see the bug. screen shot: https://www.dropbox.com/s/j0s92fkqlujripy/Screen%20Shot%202015-09-25%20at%205.55.08%20PM.png?dl=0 – angry kiwi Sep 25 '15 at 10:55
  • that's weird, I keep getting it. Here is the demo you can see it https://www.dropbox.com/s/zf2wdl2idi05bjr/map%20bug.mp4?dl=0 – angry kiwi Sep 25 '15 at 16:31
  • the code I used is the same as updated one. Firefox 40.0.3 – angry kiwi Sep 25 '15 at 16:32
  • Another look at my code https://www.dropbox.com/s/kqbc54imeibcn1a/ScreenFlow.mp4?dl=0 – angry kiwi Sep 25 '15 at 16:36
  • I know why now. I had to close firebug console when loading. it causes some script from google can not be loaded. Found the tip from this similar topic http://stackoverflow.com/questions/6660955/google-is-not-defined-when-using-google-maps-v3-in-firefox-remotely – angry kiwi Sep 25 '15 at 17:59
  • do you know how to delete individual polygon? the map.data.remove(f); will remove it all. – angry kiwi Sep 25 '15 at 18:01
  • 1
    @angry_kiwi, the following [**demo**](http://jsfiddle.net/vgrem/L5ks9yc0/) demonstrates how to delete polygons. – Vadim Gremyachev Sep 25 '15 at 20:02
1

You can use the overlaycomplete event to retrieve the paths from your drawn polygon:

google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {

    // Get overlay paths
    var paths = event.overlay.getPaths(); 
});

The paths object can be reused to create a Polygon from scratch. See the below demo. When the overlaycomplete event is triggered, get the paths from the overlay and create a new Polygon with it.

JSFiddle demo

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
  • there is a problem with that. After drawing, refresh the browser. There will be an error in the console. And the map won't load – angry kiwi Sep 25 '15 at 08:06
  • To produce the error: open the map, draw a polygon. then hard refresh the page. You will see something like this screen shot. of course turn on firebug console to see. https://www.dropbox.com/s/8d4qjzvmy7zwy7w/Screen%20Shot%202015-09-25%20at%204.34.04%20PM.png?dl=0 – angry kiwi Sep 25 '15 at 09:36
  • console.log(paths) will give me a bunch of object, how exactly I can get the coordinates from those?. – angry kiwi Sep 26 '15 at 18:10
  • Try with `getPath` instead of `getPaths` or loop through the paths (there is usually only one for a simple Polygon) and use `forEach` method of the MVCArray. – MrUpsidown Sep 27 '15 at 16:28