Google Maps API 的标记(Marker)功能允许开发者在地图上标注特定位置。标记通常由一个图标和可选的信息窗口(InfoWindow)组成,用于标识地图上的兴趣点(POI)。
// 初始化地图
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: { lat: 39.9042, lng: 116.4074 }, // 北京坐标
});
// 添加简单标记
const marker = new google.maps.Marker({
position: { lat: 39.9042, lng: 116.4074 },
map: map,
title: "北京市"
});
// 添加带信息窗口的标记
const infoWindow = new google.maps.InfoWindow({
content: "<h3>北京市</h3><p>中国首都</p>"
});
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
}
原因:
解决方案:
// 确保API已加载
if (typeof google !== 'undefined') {
// 检查坐标是否有效
if (marker.getPosition() instanceof google.maps.LatLng) {
// 确保标记已关联到地图
marker.setMap(map);
}
}
原因:
解决方案:
// 使用正确的图标路径
const marker = new google.maps.Marker({
position: { lat: 39.9042, lng: 116.4074 },
map: map,
icon: {
url: "path/to/icon.png",
scaledSize: new google.maps.Size(40, 40) // 控制图标大小
}
});
原因:
解决方案:
// 确保正确添加事件监听
google.maps.event.addListener(marker, 'click', function() {
console.log('Marker clicked');
});
// 或者使用新API
marker.addListener("click", () => {
console.log("Marker clicked");
});
原因:
解决方案:
// 使用标记聚类库
const markers = locations.map(location => {
return new google.maps.Marker({
position: location,
map: map
});
});
// 使用MarkerClusterer库
const markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
const marker = new google.maps.Marker({
position: { lat: 39.9042, lng: 116.4074 },
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10,
fillColor: "#FF0000",
fillOpacity: 1,
strokeWeight: 2,
strokeColor: "#FFFFFF"
},
title: "自定义形状标记"
});
const marker = new google.maps.Marker({
position: { lat: 39.9042, lng: 116.4074 },
map: map,
draggable: true,
title: "可拖拽标记"
});
marker.addListener("dragend", function(event) {
console.log("标记被拖拽到新位置: ", event.latLng.lat(), event.latLng.lng());
});
const marker = new google.maps.Marker({
position: { lat: 39.9042, lng: 116.4074 },
map: map,
animation: google.maps.Animation.BOUNCE
});
// 2秒后停止动画
setTimeout(() => {
marker.setAnimation(null);
}, 2000);
通过合理使用Google Maps API的标记功能,可以创建丰富、交互性强的地图应用。
没有搜到相关的文章