我正在使用gmaps.js进行Google Maps API。目标是使用用户地理位置创建地图并创建新标记。像“嗨!你在这里!”这样的东西。
地图和地理位置工作正常,但使用当前用户坐标创建新标记对我来说是一个问题。
这是代码:
// public/core.js
//Creating map
var map;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: 0,
lng: 0,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false
});
// Define user location
GMaps.geolocate({
success: function(position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
},
error: function(error) {
alert('Geolocation failed: '+error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
}
});
// Creating marker of user location
map.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
title: 'Lima',
click: function(e) {
alert('You clicked in this marker');
},
infoWindow: {
content: '<p>You are here!</p>'
}
});
});
答案 0 :(得分:0)
问题是,您对map.addMarker
的调用假定上面的函数GMaps.geolocate
已成功,而实际上position
只会设置一次success
函数解析:
// public/core.js
//Creating map
var map;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: 0,
lng: 0,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false
});
// Define user location
GMaps.geolocate({
success: function(position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
// Creating marker of user location
map.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
title: 'Lima',
click: function(e) {
alert('You clicked in this marker');
},
infoWindow: {
content: '<p>You are here!</p>'
}
});
},
error: function(error) {
alert('Geolocation failed: '+error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
}
});
});