使用Geolocation以引导模式加载地图,标记不会居中
Using Geolocation to load a map in a bootstrap modal, the marker is not centered
我正试图在基于地理位置的引导模式中加载的地图中居中放置一个标记,以获取用户的当前位置。剩下的已经在小提琴里解释了
JS小提琴
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");
});
}
任何帮助都将不胜感激。
在触发调整大小事件之前存储地图的中心,并在触发调整尺寸事件之后重新分配中心:
$('#locate').on('shown.bs.modal', function () {
var center=map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
https://jsfiddle.net/doktormolle/9tr8dmax/
相关文章:
- 谷歌地图固定位置覆盖
- chrome扩展中的navigator.geolocation.getCurrentPosition
- 不显示带有本地json文件数据的谷歌地图脚本
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 谷歌地图标记不会显示
- 无法在JS中显示谷歌地图
- 科尔多瓦页面类应用程序中的多个谷歌地图
- 需要帮助谷歌地图方向面板在FancyBox中显示
- 是否可以控制获取哪些Google地图脚本(JavaScript API)
- 在谷歌地图上获取事件的x,y坐标
- 谷歌地图API v3不适用于移动浏览器或PhoneGap
- 模拟谷歌地图中的点击
- geolocation-marker.js conflict with markerclusterer.js
- 如何知道哪个标记被谷歌地图点击了
- 谷歌地图JS API+JSON-多个标记没有显示
- 缓存谷歌地图数据
- 谷歌地图劫持了iphone's滚动(触摸事件)-如何恢复
- 在百度地图中显示navigator.geolocation.getCurrentPosition
- 使用Geolocation以引导模式加载地图,标记不会居中
- 传单地图:使用navigator.geolocation.watchPosition更新标记