我正在尝试将基于地理定位的加载在引导模式中的地图中的标记居中,以获取用户的当前位置。其余部分已在这个小提琴中得到解释...... 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">×</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");
});
}
非常感谢任何帮助。
答案 0 :(得分:0)
在触发调整大小事件之前存储地图的中心,并在触发调整大小事件后重新指定中心:
$('#locate').on('shown.bs.modal', function () {
var center=map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});