在我的网站上,我有一张谷歌地图,可以显示我去过的国家/地区标记。有没有办法将它们变成超链接,以便当用户点击这些标记时,它会将它们引导到包含来自该特定国家/地区的照片的网页? 这是我的代码:
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: 51.491217, lng: -0.142822};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 1,
streetViewControl: false
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
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());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
geocoder = new google.maps.Geocoder();
function getCountry(country) {
geocoder.geocode( { 'address': country }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 200);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getCountry('France');
getCountry('Sweden');
getCountry('Croatia');
getCountry('New Zealand');
getCountry('Laos');
getCountry('Vietnam');
getCountry('Tonga');
getCountry('Vanuatu');
getCountry('France');
getCountry('Indonesia');
getCountry('Malaysia');
getCountry('Samoa');
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
答案 0 :(得分:1)
只需在标记中添加一个事件监听器即可。所以这样的事情会起作用:
marker.addListener('click', function() {
window.location.href = 'http://example.com';
});
有关标记上事件监听器的更多示例,请参阅此处的文档:https://developers.google.com/maps/documentation/javascript/markers#animate