1

i am using gmaps.js (https://github.com/hpneo/gmaps)

I want to add a Marker on the map on clicking a location on the map. If a user clicks on a second location the previous marker should move to the new place or be removed and replaced with a new marker.

Now sure if this is supported by the Lib.

http://bakasura.in/startupsradar/add.html

$(document).ready(function () {
    var map = new GMaps({
        div: '#map',
        lat: 13.00487,
        lng: 77.576729,
        zoom: 13
    });

    map.addMarker({
        lat: 13.00487,
        lng: 77.576729,
        title: 'Mink7',
        infoWindow: {
            content: 'HTML Content'
        }
    });
    /*
    GMaps.geolocate({
        success: function (position) {
            map.setCenter(position.coords.latitude, position.coords.longitude);
        },
        error: function (error) {
            alert('Geolocation failed: ' + error.message);
        },
        not_supported: function () {
            alert("Your browser does not support geolocation");
        },
        always: function () {
            //alert("Done!");
        }
    });
    */
});
4

2 回答 2

3
google.maps.event.addListener(_map, "click", function(event) {
    if(_marker) {
        _marker.setPosition(event.latLng);
    } else {  
        _marker = new google.maps.Marker({
            position: event.latLng,
            map: _map,
            title: "myTitle"
        });
    }
});

刚刚看到另一个答案,如果您不想每次都创建标记,请使用它...... _marker应该是一个全局变量。

于 2012-06-23T09:08:14.700 回答
2

就个人而言,我使用标记的全局变量(或者如果我需要更多标记并且我想稍后访问它们,则使用数组),以便我可以删除它并在其他地方重新创建它。

// instantiate your var map
// ...

google.maps.event.addListener(map, "click", function(event) {
    if(markermap) {
        markermap.setMap(null);
    }

    markermap = new google.maps.Marker({
        position: event.latLng,
        map: myMap,
        title: "myTitle"
    });
});
于 2012-06-23T08:55:47.077 回答