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!");
        }
    });
    */
});

2 Answers 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"
        });
    }
});

Just saw the other answer, use this if you dont want to create a marker everytime.. _marker should be a global variable.

Sign up to request clarification or add additional context in comments.

Comments

2

Personally, I do it using a global variable for the marker (or an array if I need more markers and I want to access them later), so that I can delete it and recreate it somewhere else.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.