Google Maps v3 set single marker point on map click

Right now I have google map code that will set a single marker on a map. What I want is for that single marker to be moved to whatever coordinates the user clicks on. I only want 1 marker on the map, so I need that single marker to be moved to whatever location is clicked. Any help is appreciated. Thanks!

    var initialLocation;
    var siberia = new google.maps.LatLng(60, 105);
    var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
    var browserSupportFlag =  new Boolean();



    function initialize() {
        var myOptions = {
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.HYBRID
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        myListener = google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
            google.maps.event.removeListener(myListener);
        });
        google.maps.event.addListener(map, 'drag', function(event) {
            placeMarker(event.latLng);
            google.maps.event.removeListener(myListener);
        });

        // Try W3C Geolocation (Preferred)
        if(navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeolocation(browserSupportFlag);
            });
            // Try Google Gears Geolocation
        } else if (google.gears) {
            browserSupportFlag = true;
            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeoLocation(browserSupportFlag);
            });
            // Browser doesn't support Geolocation
        } else {
            browserSupportFlag = false;
            handleNoGeolocation(browserSupportFlag);
        }

        function handleNoGeolocation(errorFlag) {
            if (errorFlag === true) {
                alert("Geolocation service failed.");
                initialLocation = newyork;
            } else {
                alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
                initialLocation = siberia;
            }
        }

        function placeMarker(location) {
            var marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable: true
            });
            map.setCenter(location);
            var markerPosition = marker.getPosition();
            populateInputs(markerPosition);
            google.maps.event.addListener(marker, "drag", function (mEvent) {
                populateInputs(mEvent.latLng);
            });
        }
        function populateInputs(pos) {
            document.getElementById("t1").value=pos.lat()
            document.getElementById("t2").value=pos.lng();
        }
    }

Answers


<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #map_canvas {height:600px;width:800px}
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
        var map;
        var markersArray = [];

        function initMap()
        {
            var latlng = new google.maps.LatLng(41, 29);
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            // add a click event handler to the map object
            google.maps.event.addListener(map, "click", function(event)
            {
                // place a marker
                placeMarker(event.latLng);

                // display the lat/lng in your form's lat/lng fields
                document.getElementById("latFld").value = event.latLng.lat();
                document.getElementById("lngFld").value = event.latLng.lng();
            });
        }
        function placeMarker(location) {
            // first remove all markers if there are any
            deleteOverlays();

            var marker = new google.maps.Marker({
                position: location, 
                map: map
            });

            // add marker in markers array
            markersArray.push(marker);

            //map.setCenter(location);
        }

        // Deletes all markers in the array by removing references to them
        function deleteOverlays() {
            if (markersArray) {
                for (i in markersArray) {
                    markersArray[i].setMap(null);
                }
            markersArray.length = 0;
            }
        }
    </script>
</head>

<body onload="initMap()">
    <div id="map_canvas"></div>
    <input type="text" id="latFld">
    <input type="text" id="lngFld">
</body>
</html>

The current answers do a lot more work than is necessary by removing and re-adding the marker(s). The best way to do this is to use the setPosition() function that the Google Maps API provides for this purpose.

Here is your code modified to use setPosition() to move the pointer:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #map_canvas { height:600px; width:800px }
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
    var initialLocation;
    var siberia = new google.maps.LatLng(60, 105);
    var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
    var browserSupportFlag =  new Boolean();

    function initialize() {
        var myOptions = {
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.HYBRID
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker;

        myListener = google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
        });
        google.maps.event.addListener(map, 'drag', function(event) {
            placeMarker(event.latLng);
        });

        // Try W3C Geolocation (Preferred)
        if(navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeolocation(browserSupportFlag);
            });
            // Try Google Gears Geolocation
        } else if (google.gears) {
            browserSupportFlag = true;
            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeoLocation(browserSupportFlag);
            });
            // Browser doesn't support Geolocation
        } else {
            browserSupportFlag = false;
            handleNoGeolocation(browserSupportFlag);
        }

        function handleNoGeolocation(errorFlag) {
            if (errorFlag === true) {
                alert("Geolocation service failed.");
                initialLocation = newyork;
            } else {
                alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
                initialLocation = siberia;
            }
        }

        function placeMarker(location) {
            if (marker) {
                marker.setPosition(location);
            } else {
               marker = new google.maps.Marker({
                    position: location,
                    map: map,
                    draggable: true
                });
                google.maps.event.addListener(marker, "drag", function (mEvent) {
                    populateInputs(mEvent.latLng);
                });
            }
            populateInputs(location);
        }

        function populateInputs(pos) {
            document.getElementById("t1").value=pos.lat()
            document.getElementById("t2").value=pos.lng();
        }
    }

    </script>
</head>

<body onload="initialize()">
    <div id="map_canvas"></div>
    <input type="text" id="t1">
    <input type="text" id="t2">
</body>
</html>

Make a global javascript variable "marker".

Then in your listener add the if marker exists statement and remove it if true

myListener = google.maps.event.addListener(map, 'click', function(event) {
            if(marker){marker.setMap(null)}
            placeMarker(event.latLng);
            google.maps.event.removeListener(myListener);
        });

You can try:

google.maps.event.addListener(map, 'click', function(event){
        var marker_position = event.latLng;   
marker = new google.maps.Marker({
                map: map,
                draggable: false
            }); 
       marker.setPosition(marker_position);
})

try this

if (marker) { marker.setMap(null) }

marker = new google.maps.Marker({ position: event.latLng, map: map });

Burak Erdem answer works fine, but actually you dont need and array to do that, it is enough one var since it is only one last marker, becouse when you set a new one, you delete inmediatly the last one. I did it with this few lines and it worked fine:

        var map;
        var lastMarker;
        function initialize() {
            var map_canvas = document.getElementById('map_canvas');
            var map_options = {
                center: new google.maps.LatLng(-25.363882, 131.044922),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(map_canvas, map_options)
            google.maps.event.addListener(map, 'click', function(event) {
                placeMarker(event.latLng);
            });
        }

        function placeMarker(location) {
            if (lastMarker != null)
                lastMarker.setMap(null);
            var marker = new google.maps.Marker({
                position: location,
                map: map
            });
            lastMarker = marker;
        }

        google.maps.event.addDomListener(window, 'load', initialize);

I accomplished this with the following:

// create a new marker
var marker = new google.maps.Marker({
 });
//add listener to set the marker to the position on the map
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng);
marker.setMap(map);
marker.setAnimation(google.maps.Animation.DROP);
});

It creates a marker and then move it to each mouse click location... I also added a drop marker animation as well.

Instead of creating multiple markers this creates one marker and moves it to the clicked location.


Need Your Help

Visual Studio - suddenly cannot debug tests

visual-studio visual-studio-2012 visual-studio-2017 visual-studio-debugging vs-unit-testing-framework

I'm not sure what I did, but all of a sudden, my Visual Studio 2012 will not debug any tests.

Node.js: Cannot access server from different device on the same network

node.js

NOTE: There are some others who have had similar problems, but those were solved by fixing small tidbits in the code involving how the server was listening (in examples that I've seen they put '127...