在点击 google 地图上添加标记
Adding marker on click google maps
我希望只有在按下“添加标记”按钮后才能通过单击在地图上添加标记,但该按钮不起作用,该功能甚至在我按下按钮之前就已运行。
https://jsfiddle.net/snoLg0tp/
<input id="add-markers" type="button" value="Add marker" />
function initMap() {
const haightAshbury = { lat: 37.769, lng: -122.446 };
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: haightAshbury,
mapTypeId: "terrain",
});
// This event listener will call addMarker() when the map is clicked.
map.addListener("click", (event) => {
addMarker(event.latLng);
});
document
.getElementById("add-markers")
.addEventListener("click", addMarker);
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function addMarker(position) {
const marker = new google.maps.Marker({
position,
map,
});
可以制作一个可以用按钮或在 addMarker 函数中切换的标志。
let shouldAddMarker = true;
...
document
.getElementById("add-markers")
.addEventListener("click", addMarker => {shouldAddMarker = !shouldAddMarker});
...
function addMarker(position) {
if (shouldAddMarker) {
const marker = new google.maps.Marker({
position,
map,
});
markers.push(marker);
}
}
见https://jsfiddle.net/x4twfaze/2/
如果您只想在每次单击按钮后添加一个标记。您可以将其更改为:
let shouldAddMarker = false;
...
document
.getElementById("add-markers")
.addEventListener("click", addMarker => {shouldAddMarker = true});
...
function addMarker(position) {
if (shouldAddMarker) {
const marker = new google.maps.Marker({
position,
map,
});
markers.push(marker);
shouldAddMarker = false;
}
}
我希望只有在按下“添加标记”按钮后才能通过单击在地图上添加标记,但该按钮不起作用,该功能甚至在我按下按钮之前就已运行。 https://jsfiddle.net/snoLg0tp/
<input id="add-markers" type="button" value="Add marker" />
function initMap() {
const haightAshbury = { lat: 37.769, lng: -122.446 };
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: haightAshbury,
mapTypeId: "terrain",
});
// This event listener will call addMarker() when the map is clicked.
map.addListener("click", (event) => {
addMarker(event.latLng);
});
document
.getElementById("add-markers")
.addEventListener("click", addMarker);
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function addMarker(position) {
const marker = new google.maps.Marker({
position,
map,
});
可以制作一个可以用按钮或在 addMarker 函数中切换的标志。
let shouldAddMarker = true;
...
document
.getElementById("add-markers")
.addEventListener("click", addMarker => {shouldAddMarker = !shouldAddMarker});
...
function addMarker(position) {
if (shouldAddMarker) {
const marker = new google.maps.Marker({
position,
map,
});
markers.push(marker);
}
}
见https://jsfiddle.net/x4twfaze/2/
如果您只想在每次单击按钮后添加一个标记。您可以将其更改为:
let shouldAddMarker = false;
...
document
.getElementById("add-markers")
.addEventListener("click", addMarker => {shouldAddMarker = true});
...
function addMarker(position) {
if (shouldAddMarker) {
const marker = new google.maps.Marker({
position,
map,
});
markers.push(marker);
shouldAddMarker = false;
}
}