gpt4 book ai didi

javascript - 重新定位谷歌地图的html链接

转载 作者:行者123 更新时间:2023-12-03 09:33:54 38 4
gpt4 key购买 nike

在我正在制作的个人博客网站上,我将背景设置为谷歌地图,并在顶部有一个较小的div谈论我去过的地方等。我想做的是有一个像“显示place in google map”,点击后背景 map 会更新到对应位置。

我尝试编写 JavaScript 代码

<script> function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
scrollwheel: false,
center: new google.maps.LatLng(34.0722, -118.4441),
zoom: 14,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
streetViewControl: false,
panControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);

var marker = new google.maps.Marker();
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script type="text/javascript">
window.onload = function() {
var a = document.getElementsByClassName("map-link");
a.onclick = function() {
marker.setMap(map);
}
}
</script>

<a class="map-link" href="javascript:void(0)"> Show in Google Maps </a>

类似的事情,但我没有看到任何结果。有人知道该怎么做吗?

最佳答案

  1. 使用map.setCenter更改 map 的中心。
  2. getElementsByClassName 返回 DOM 元素数组。

    google.maps.event.addDomListener(document.getElementsByClassName("map-link")[0], 'click', function (e) { map.setCenter(new google.maps.LatLng(42, -72));});

proof of concept fiddle

代码片段:

function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
scrollwheel: false,
center: new google.maps.LatLng(34.0722, -118.4441),
zoom: 14,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
streetViewControl: false,
panControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addDomListener(document.getElementsByClassName("map-link")[0], 'click', function(e) {
map.setCenter(new google.maps.LatLng(42, -72));
});
google.maps.event.addDomListener(document.getElementsByClassName("map-link")[1], 'click', function(e) {
map.setCenter(new google.maps.LatLng(41, -72.1));
});
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<ul>
<li><a class="map-link" href="javascript:void(0)"> Show in Google Maps </a>
</li>
<li><a class="map-link" href="javascript:void(0)"> Show another place in Google Maps </a>
</li>
</ul>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>

关于javascript - 重新定位谷歌地图的html链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31396571/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com