我正在学习如何使用 Google 地理定位 API。我的钥匙可以告诉我纬度和经度,我得到了如图所示的确切位置的地图。但我需要的是没有红色目的地标记的地图。
我不知道是否可以用这个API来做到这一点。
async function getApproximateLocation(apiKey) {
try {
const response = await fetch('https://www.googleapis.com/geolocation/v1/geolocate?key=' + apiKey, {
method: 'POST'
});
const data = await response.json();
return {
latitude: data.location.lat,
longitude: data.location.lng
};
} catch (error) {
console.error('Error al obtener la ubicación aproximada:', error);
throw error;
}
}
.
const loc = userLocation ? `${userLocation.latitude},${userLocation.longitude}` : `${ipInfo.latitude},${ipInfo.longitude}`;
const mapUrl = `https://maps.google.com/maps?q=${loc}&z=12&output=embed`;
mapIframe.src = mapUrl;
mapContainer.style.display = 'block';
marker.setMap(null)
此方法从地图上删除标记。将标记的地图属性设置为 null 可有效地将标记与地图分离,使其在添加后立即消失。
更多拘留信息在这里
此代码可以删除标记
const marker = new google.maps.Marker({
position: { lat: location.latitude, lng: location.longitude },
map: map
});
// Remove the marker immediately after it is added to the map
marker.setMap(null);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Google Maps Example</title>
<script>
function loadGoogleMapsApi() {
var apiKey = document.getElementById('api-key').value;
var script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=initializeMap`;
document.head.appendChild(script);
}
document.addEventListener('DOMContentLoaded', loadGoogleMapsApi);
</script>
<script src="map.js"></script>
</head>
<body>
<!-- Replace with your actual API key -->
<input type="hidden" id="api-key" value="{API key}">
<div id="map" style="height: 800px; width: 100%;"></div>
</body>
</html>
map.js
async function getApproximateLocation(apiKey) {
try {
const response = await fetch('https://www.googleapis.com/geolocation/v1/geolocate?key=' + apiKey, {
method: 'POST'
});
const data = await response.json();
return {
latitude: data.location.lat,
longitude: data.location.lng
};
} catch (error) {
console.error('Error obtaining approximate location:', error);
throw error;
}
}
function initializeMap() {
const apiKey = document.getElementById('api-key').value;
getApproximateLocation(apiKey).then(location => {
const mapOptions = {
center: new google.maps.LatLng(location.latitude, location.longitude),
zoom: 12
};
const map = new google.maps.Map(document.getElementById('map'), mapOptions);
const marker = new google.maps.Marker({
position: { lat: location.latitude, lng: location.longitude },
map: map
});
// Remove the marker immediately after it is added to the map
marker.setMap(null);
}).catch(error => {
console.error('Error initializing map:', error);
});
}