我正确地获取了设备的位置并将地图居中,我也成功创建了一个标记,但我没有正确地组合这两个标记。我想将标记设置为设备的当前位置。到目前为止,这是我的代码:
let map, infoWindow;
async function initMap() {
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -33.9778791, lng: 22.4188544 },
zoom: 15,
disableDefaultUI: true
});
infoWindow = new google.maps.InfoWindow();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
map.setCenter(pos);
const marker = new AdvancedMarkerElement({
map: map,
position: pos,
});
infoWindow.setPosition(pos);
infoWindow.setContent("Location found.");
infoWindow.open(map, marker);
},
() => {
handleLocationError(true, infoWindow, map.getCenter());
}
);
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? "Error: The Geolocation service failed."
: "Error: Your browser doesn't support geolocation."
);
infoWindow.open(map);
}
window.initMap = initMap;
使用这段代码什么也不会发生。屏幕是空的。使用添加高级标记中的代码,标记将显示在硬编码位置。使用Geolocation中的代码,地图会加载设备的位置,而无需标记。
如何正确完成此操作?
我忘记调用 initMap(),现在我调用它,标记加载成功。另外,我添加了mapId。这是更正后的代码:
let map, infoWindow;
async function initMap() {
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -33.9778791, lng: 22.4188544 },
zoom: 15,
mapId: "DEMO_MAP_ID",
disableDefaultUI: true
});
infoWindow = new google.maps.InfoWindow();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
map.setCenter(pos);
const marker = new AdvancedMarkerElement({
map: map,
position: pos,
});
infoWindow.setPosition(pos);
infoWindow.setContent("Location found.");
infoWindow.open(map, marker);
},
() => {
handleLocationError(true, infoWindow, map.getCenter());
}
);
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? "Error: The Geolocation service failed."
: "Error: Your browser doesn't support geolocation."
);
infoWindow.open(map);
}
window.initMap = initMap;
initMap();