我正在尝试获取用户当前位置并将这些纬度/经度坐标传递给地图。该地图将用作网站背景图片。
我使用此代码取得了部分成功:
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
xss =position.coords.latitude +
"," + position.coords.longitude;
}
var position = [32.5590985,35.8415147];
现在我希望xss
的值在此变量中:
var position = [32.5590985,35.8415147];
基本上我试图从函数中获取值,但没有成功。
我该如何从函数内部获取值?
HTML
<div id="googlemaps"></div>
JS代码
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
xss =position.coords.latitude +
"," + position.coords.longitude;
}
var position = [32.5590985,35.8415147];
function initialize() {
var myOptions = {
zoom: 17,
streetViewControl: false,
scaleControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('googlemaps'),
myOptions);
latLng = new google.maps.LatLng(position[0], position[1]);
map.setCenter(latLng);
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP
});
}
google.maps.event.addDomListener(window, 'load', initialize);
答案 0 :(得分:1)
如何在position
函数中设置showPosition
变量的值?
var position;
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(pos) {
position = [pos.coords.latitude, pos.coords.longitude];
}
答案 1 :(得分:0)
假设navigator.geolocation.getCurrentPosition
是异步的,这看起来像是经典&#34;从异步请求中获取结果&#34;问题。有关详细解答,请参阅https://stackoverflow.com/a/14220323/380487。