我的问题是每次我打开网站;第一次地图没有显示,重新加载/ referh后它工作并显示地图。
这是我的谷歌地图代码:
<script type="text/javascript">
var map;
var infowindow;
function initialize(position) {
//var pyrmont = new google.maps.LatLng(48.195201,16.369547);
var pyrmont = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var a = new google.maps.Marker({position: pyrmont,map: map,icon:'catal.png'});
var request = {
location: pyrmont,
radius: 500,
types: ['restaurant']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS){
alert('zero results near this location');
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent( place.name
+'<br/>'+place.vicinity);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', function(){
navigator.geolocation.getCurrentPosition(initialize);
});
</script>
在这里我如何将它与jquery一起使用:
<div data-role="page" id="restaurant">
<div data-role="header">
<a href="index.html" data-icon="arrow-l">Back</a>
<h1>Restaurants</h1>
</div>
<div data-role="content">
<div id="map" style="width:400px; height:400px;"></div>
</div>
</div>
答案 0 :(得分:3)
您正在等待window.load
事件触发,该事件仅在整页刷新时触发。这是违规代码:
google.maps.event.addDomListener(window, 'load', function(){
navigator.geolocation.getCurrentPosition(initialize);
});
您可以使用jQuery绑定到pageinit
页面的#restautant
事件:
$(document).delegate('#restaurant', 'pageinit', function () {
navigator.geolocation.getCurrentPosition(initialize);
});
这将在初始化initialize()
伪页面时触发#restaurant
函数(每次将其添加到DOM时都会发生一次)。
以下是pageinit
事件(以及所有其他jQuery Mobile事件)的文档:http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/events.html