简体   繁体   English

从内部函数js获取变量值

[英]getting variable value from inside function js

I am trying to get user current location and pass those latitude/longitude coordinates to a map. 我正在尝试获取用户当前位置,并将那些经度/纬度坐标传递给地图。 The map will be used as a website background image. 该地图将用作网站背景图片。

I was partially successful with this code: 我在此代码上取得了部分成功:

  navigator.geolocation.getCurrentPosition(showPosition);

    function showPosition(position) {
        xss =position.coords.latitude + 
        "," + position.coords.longitude; 


  }
var position = [32.5590985,35.8415147];

Now I want the value of xss to be inside this variable: 现在,我希望xss的值在此变量内:

var position = [32.5590985,35.8415147];

basically I was trying to get the values from the function but without success. 基本上,我试图从函数中获取值,但没有成功。

How should I go about getting a value from inside the function? 我应该如何从函数内部获取值?

HTML HTML

<div id="googlemaps"></div>

JS Code 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);

How about you set the value of position variable from inside the showPosition function? 您如何从showPosition函数内部设置position变量的值?

var position;

navigator.geolocation.getCurrentPosition(showPosition);

function showPosition(pos) {
  position = [pos.coords.latitude, pos.coords.longitude];
}

Assuming navigator.geolocation.getCurrentPosition is asynchronous, this looks like a classic "Get results from an asynchronous request" problem. 假设navigator.geolocation.getCurrentPosition是异步的,这看起来像是经典的“从异步请求获取结果”问题。 Please see https://stackoverflow.com/a/14220323/380487 for a detailed answer. 请参阅https://stackoverflow.com/a/14220323/380487了解详细答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM