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

javascript - Google Maps API v3 save and reuse shape from drawingManager - Stack Overflow

programmeradmin3浏览0评论

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=";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>  

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./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>  
Share Improve this question edited Sep 25, 2015 at 16:29 angry kiwi asked Sep 23, 2015 at 12:29 angry kiwiangry kiwi 11.5k28 gold badges123 silver badges167 bronze badges 2
  • There is a polygonplete event developers.google./maps/documentation/javascript/3.exp/… you should be able to get your polygon path and save this data for future use. – MrUpsidown Commented Sep 23, 2015 at 16:33
  • @MrUpsidown how to get the polygon path? and how to reinstate it ? – angry kiwi Commented Sep 23, 2015 at 18:51
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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

google.maps.event.addListener(drawingManager, 'overlayplete', 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 overlayplete event is triggered, get the paths from the overlay and create a new Polygon with it.

JSFiddle demo

发布评论

评论列表(0)

  1. 暂无评论