Ваша проблема в том, что переменная marker
внутри функции jquery .ready
является локальной для этой функции (и отличается от marker
, который находится в глобальной области, созданной функцией initMap
).
Объявите marker
в глобальной области видимости (например, map
и infoWindow
), и это будет работать.
<div id="map"></div>
<script>
var map, infoWindow;
var marker; // put marker in global scope (remove from .ready function)
подтверждение концепции скрипта
фрагмент кода:
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>