alireza darvishi
alireza darvishi

Reputation: 49

How to set new coordinate for google maps marker?

By this code I can put a marker on map by current location data.

After that, When user clicked on map I want to show a marker and set new coordinate. (delete before marker)

But when I click on map I see I have two marker and old marker is not deleted.

How can I set new coordinate for first marker?

Note: If I have not first marker, I should create first marker by click.(I do that)

Map:

    <div id="map"></div>
            <script>
    var map, infoWindow;

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 28.961856892883443,
            lng: 50.83683013916016
        },
        zoom: 15,
        gestureHandling: 'greedy',
    });
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var location = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

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


        }, function () {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}


function handleLocationError(browserHasGeolocation, infoWindow, location) {
    alert("Error");
    infoWindow.open(map);
}


// New marker by click on map

$(document).ready(function () {
    var marker;

    function placeMarker(location) {
        if (marker) {
            marker.setPosition(location);
        } else {
            marker = new google.maps.Marker({
                position: location,
                map: map
            });
        }
    }

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

</script>
<script async defer
src = "https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&language=fa&callback=initMap" >
</script>

Note: I want just one marker in map.

Upvotes: 0

Views: 991

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Your issue is that the marker variable inside the jquery .ready function is local to that function (and different from the marker that is in the global scope created by the initMap function).

Declare the marker in the global scope (like map and infoWindow) and it works.

<div id="map"></div>
        <script>
var map, infoWindow;
var marker; // put marker in global scope (remove from .ready function)

proof of concept fiddle

code snippet:

html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
<script>
  var map, infoWindow;
  var marker;

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: 28.961856892883443,
        lng: 50.83683013916016
      },
      zoom: 15,
      gestureHandling: 'greedy',
    });
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var location = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

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


      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

  function handleLocationError(browserHasGeolocation, infoWindow, location) {
    alert("Error");
    infoWindow.open(map);
  }

  // New marker by click on map
  $(document).ready(function() {
    function placeMarker(location) {
      if (marker) {
        marker.setPosition(location);
      } else {
        marker = new google.maps.Marker({
          position: location,
          map: map
        });
      }
    }

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

</script>

Upvotes: 2

Related Questions