是否可以通过url hash' name'触发标记信息。 而不是一个数字。 类似的帖子:Trigger Google map info window with URL hash
var urlhash = window.location.hash.replace('#','');
我用这种方式放置标记:
/* Google Map */
function googleMap(){
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = [];
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
map.panTo(marker.getPosition());
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
};
})(marker, i));
}
if(urlhash){
google.maps.event.trigger(markers[urlhash], 'click');
}
}
例如/index.html#bondi-beach而不是例如/index.html#1 非常感谢任何帮助!
答案 0 :(得分:1)
使用#hash作为数组/ hashmap的索引:
markers[(locations[i][0]).toLowerCase()] = marker;
然后:
if(urlhash){
google.maps.event.trigger(markers[urlhash.toLowerCase()], 'click');
}
代码段
var urlhash = window.location.hash.replace('#', '');
// for code snippet only
urlhash = "bondi%20beach";
// ===================
var markers = [];
/* Google Map */
function googleMap() {
console.log(urlhash);
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers[(locations[i][0]).toLowerCase()] = marker;
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
map.panTo(marker.getPosition());
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
};
})(marker, i));
}
if (urlhash) {
google.maps.event.trigger(markers[decodeURI(urlhash.toLowerCase())], 'click');
}
}
google.maps.event.addDomListener(window, "load", googleMap);
&#13;
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div id="map"></div>
&#13;