我对编程很陌生。我试图在Google Maps API v3上放置四个随机标记,并在网页上添加一个经典按钮,将按照这些标记逐一对中地图。如果中心位于第三个标记上,则下一次单击应将地图置于第一个标记等中心。 除了经典的javascript和html之外,我不能使用jquery或任何其他库。
答案 0 :(得分:0)
使用Previous SO Answer中的代码并将map.panTo(marker.getPosition());
添加到现有代码中,将点击基于标记列表的地图或点击按钮。
查看全屏以获得更好的结果
// Locations: [title, lat, long, number]
var locations = [
['Bar Termini', 51.51367, -0.12981, 1],
['French House', 51.51272, -0.13170, 2],
['Mark\'s Bar', 51.51133, -0.13563, 3],
['Hakkasan (bar)', 51.51017, -0.14474, 4],
['Bar Américain at Brasserie Zédel', 51.51027, -0.14474, 5],
['Experimental Cocktail Club', 51.51193, -0.13103, 6],
['Milk & Honey', 51.51377, -0.13653, 7],
['Blind Pig', 51.51379, -0.13668, 8],
['Opium', 51.51176, -0.13145, 9]
];
var gmarkers = [];
// Map Settings
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 16,
center: new google.maps.LatLng(51.51367, -0.12981),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow;
var marker, i;
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,
label: String(locations[i][3])
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
map.panTo(marker.getPosition());
}
})(marker, i));
}
function centerMap(obj) {
google.maps.event.trigger(gmarkers[obj], 'click');
}
function pickRandom() {
var rnd = Math.floor(Math.random() * 7) + 0;
google.maps.event.trigger(gmarkers[rnd], 'click');
}
#map {
height: 400px;
width: 100%;
}
a {
cursor: pointer;
}
<div data-role="page" id="map_result">
<div data-role="header" data-position="fixed">
<h1>Multiple Marker</h1>
</div>
<div data-role="content" style="padding:0;">
<div id="map"></div>
<button onclick="pickRandom()">Random Select</button>
<div id="list">
<ol>Click on Link Below
<li onclick="centerMap(0)">
<a>Bar Termini</a>
</li>
<li onclick="centerMap(1)">
<a>French House</a>
</li>
<li onclick="centerMap(2)">
<a>Mark's Bar</a>
</li>
<li onclick="centerMap(3)">
<a>Hakkasan (bar)</a>
</li>
<li onclick="centerMap(4)">
<a>Bar Americain at Brasserie Zedel</a>
</li>
<li onclick="centerMap(5)">
<a>Experimental Cocktail Club</a>
</li>
<li onclick="centerMap(6)">
<a>Milk & Honey</a>
</li>
<li onclick="centerMap(7)">
<a>Blind Pig</a>
</li>
<li onclick="centerMap(8)">
<a>Opium</a>
</li>
</ol>
</div>
</div>
</div>
<script type="text/javascript" src="https://maps.google.com/maps/api/js"></script>