gpt4 book ai didi

javascript - 使用地理定位在引导模式中加载 map ,标记未居中

转载 作者:行者123 更新时间:2023-12-03 07:20:14 25 4
gpt4 key购买 nike

我试图将基于地理位置的引导模式中加载的 map 中的标记居中,以获取用户的当前位置。其余的已经在这个 fiddle 中解释了......
JS FIDDLE

HTML:

<a href="#locate" data-toggle="modal">Open Modal</a>
<div id="locate" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title-contact">My Location</h4>
</div>
<div class="modal-body">
<div id="map"></div>
</div>
</div>
</div>
</div>

JavaScript:

function initMap(){

var loc = {lat:0,lng:0};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert("Geolocation is not supported by this browser.");
}

function showPosition(position){
loc.lat=position.coords.latitude;
loc.lng=position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(loc.lat, loc.lng);
console.log(latLng);
if (geocoder) {
geocoder.geocode({ 'latLng': latLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var markerOptions = new google.maps.Marker({
clickable: true,
flat: true,
map: map,
position: results[0].geometry.location,
title: "You are here",
visible:true,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
});
var marker = new google.maps.Marker(markerOptions);
map.setCenter(results[0].geometry.location);
}
else {
console.log("Geocoding failed: " + status);
}
});
}
}

var latLong = new google.maps.LatLng(loc.lat, loc.lng);
var mapOptions = {
center: latLong,
useCurrentLocation : true,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

var bounds = new google.maps.LatLngBounds();
bounds.extend(latLong);
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
if (map.getZoom() > 16) map.setZoom(16);
google.maps.event.removeListener(listener);
});

$('#locate').on('shown', function () {
google.maps.event.trigger(map, "resize");

});
}

任何帮助将不胜感激。

最佳答案

在触发调整大小事件之前存储 map 的中心,并在触发调整大小事件后重新分配中心:

$('#locate').on('shown.bs.modal', function () {
var center=map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});

https://jsfiddle.net/doktormolle/9tr8dmax/

关于javascript - 使用地理定位在引导模式中加载 map ,标记未居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238635/

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