您好我有一张Google地图会自动检查用户位置并将该位置置于中心位置。我把标记放在中心有问题。当你点击某处时我正在添加标记。
我还希望在点击其他位置时清除现有标记。
var markers = [];
window.onload = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
var mapOptions = {
center: new google.maps.LatLng(21.3891, 39.8579),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// This event listener calls addMarker() when the map is
// clicked.
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addListener(map, 'click', function(e) {
document.getElementById("lat").value = (e.latLng.lat());
document.getElementById("lng").value = (e.latLng.lng());
div = document.getElementById('name');
div.style.display = "block";
div = document.getElementById('submit');
div.style.display = "block";
var element = document.getElementById('spacing');
element.style.margin = null;
});
}
#map {
height: 100%;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA-2vW1cIR0t0ZVfVdCmcxx0QEV4C3l6hk&callback=myMap"></script>
<div id="map" style="width:100%; height:505px ; z-index: 1;">
</div>
答案 0 :(得分:0)
您好将此代码添加到现有代码中以将标记添加到中心:
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
var marker = new google.maps.Marker({position:pos,animation: google.maps.Animation.BOUNCE,图标:'img / mapicon.png'});
marker.setMap(地图);
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
答案 1 :(得分:0)
对于secoind解决方案,我补充说:
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
icon: 'img/mapicon.png',
map: map
});
map.panTo(position);
markers.push(marker);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function clearMarker(position, map) {
setMapOnAll(null);
}