JavaScript Google Maps API如何将位置lat / long存储到全局变量 [英] JavaScript Google Maps API How to Store Location lat/long to Global Variable

查看:92
本文介绍了JavaScript Google Maps API如何将位置lat / long存储到全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript新手,希望实施Google提供的代码,以便在您的位置放置标记。但是,我想获取位置数据并在getCurrentPosition块之外使用它。



我的第一遍是使用lat和long实例化一个Object,并将其作为块的外部属性,并将其作为getCurrentPosition内的函数的参数:

 函数initMap(){

var pos = {
lat:42.1,
lng: -74.1
};

var map = new google.maps.Map(document.getElementById('map'),{
center:{lat:42,lng:-74},
zoom :6
});
var infoWindow = new google.maps.InfoWindow({map:map});

//尝试HTML5地理位置。
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position,pos){
pos.lat = position.coords.latitude;
pos.lng = position.coords.longitude;

map.setCenter(pos);
},function(){
handleLocationError(true,infoWindow,map.getCenter());
});
} else {
//浏览器不支持地理位置
handleLocationError(false,infoWindow,map.getCenter());


var marker = new google.maps.Marker({
position:pos,
map:map,
title:'Release Source'
});


$ / code>

这样做的效果是标记将位于对象实例化时指定的位置。这些都是占位符的值,因为我目前的位置有几个州。



'pos.lat = position.coords.latitude'and'pos.lng = position.coords。经度不会覆盖全局pos对象实例化时设置的属性值。



地图不是以我当前的位置为中心,而是基于实例化时最初分配给pos的占位符lat和long值。



当我更改为navigator.geolocation.getCurrentPosition(function(position){
...
}时,

这会删除对getCurrentPosition块内部全局pos变量的引用,它会创建一个名为pos的局部变量。




$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b

然而,标记将显示在最初的经纬度长度上,当全局变量pos被实例化时,标记被指定为占位符值。

请让我知道如何将当前纬度/长度值数据取出到getCurrentPosition块之外并进入全局pos对象中。

$ b $ getCurrentPosition方法被定义为(来自

文档):
$ b


navigator.geolocation.getCurrentPosition(success,错误[,选项]])

参数

成功 - 一个回调函数,唯一的输入参数。

error - 可选 - 一个可选的回调函数,它将PositionError对象作为唯一的输入参数。



options - 可选 - 一个可选的PositionOptions对象。


您使用它的方式会导致本地 pos 要创建的变量(值为null)。

 函数(position,pos){

只需使用一个参数创建函数签名即可:

  function(position){

程式码片段:

 函数initMap(){var infoWindow = new google.maps.InfoWindow(); var pos = {lat:42.1,lng:-74.1}; var map = new google.maps.Map(document.getElementById('map'),{center:{lat:42,lng:-74},zoom:6}); //尝试HTML5地理位置。 if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(position){pos.lat = position.coords.latitude; pos.lng = position.coords.longitude; map.setCenter(pos); var marker = new google .maps.Marker({position:pos,map:map,title:'Release Source'});},function(){handleLocationError(true,infoWindow,map.getCenter(),map);}); } else {//浏览器不支持地理位置handleLocationError(false,infoWindow,map.getCenter(),map); } function handleLocationError(input,infoWindow,center,map){infoWindow.setContent(ERROR:+ input); infoWindow.setPosition(中心); infoWindow.open(地图); }} google.maps.event.addDomListener(window,'load',initMap);  

  html,body,#map {height:100%;宽度:100%; margin:0px; < script src =https://   



概念证明小提琴


I'm new to JavaScript, and am looking to implement the code provided by Google for putting a marker at your location. However, I'd like to take the location data and use it outside of the "getCurrentPosition" block.

My first pass was to instantiate an Object with lat and long as properties outside of the block and have this as a parameter of the function inside getCurrentPosition:

function initMap() {

    var pos = {
        lat: 42.1,
        lng: -74.1
    };

    var map = new google.maps.Map(document.getElementById('map'), {
                                  center: {lat: 42, lng: -74},
                                  zoom: 6
                                  });
    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position, pos) {
                                                 pos.lat = position.coords.latitude;
                                                 pos.lng = position.coords.longitude;

                                                 map.setCenter(pos);
                                                 }, function() {
                                                    handleLocationError(true, infoWindow, map.getCenter());
                                                 });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }

    var marker = new google.maps.Marker({
                                        position: pos,
                                        map: map,
                                        title: 'Release Source'
                                        });

}

The effect of this is that the marker will be at the position specified when the object is instantiated. These are placeholder values, as my current location is several states away.

'pos.lat = position.coords.latitude' and 'pos.lng = position.coords.longitude' are not overwriting the property values as set when the global "pos" object was instantiated.

The map is not centered on my current position, but based on the placeholder lat and long values originally assigned to "pos" when instantiated.

When I change to "navigator.geolocation.getCurrentPosition(function(position) { ... }",

this removes reference to the global "pos" variable inside of the "getCurrentPosition" block. It appears a local variable named "pos" is created.

The local instance of "pos" inside of the block will have its lat and long assigned based on my current location. The map is then centered around my current location, as per instruction in the block.

The marker will, however, be shown at the original lat long that were assigned as placeholder values when the global variable "pos" was instantiated.

Please let me know how I can get the current lat/long values data outside of the "getCurrentPosition" block and into the global "pos" object.

解决方案

The getCurrentPosition method is defined as (from the documentation):

navigator.geolocation.getCurrentPosition(success[, error[, options]])

Parameters

success - A callback function that takes a Position object as its sole input parameter.

error - Optional - An optional callback function that takes a PositionError object as its sole input parameter.

options - Optional - An optional PositionOptions object.

The way you are using it causes a local pos variable to be created (with the value of null).

function(position, pos) {

Just create the function signature with a single argument:

function(position) {

code snippet:

function initMap() {
  var infoWindow = new google.maps.InfoWindow();
  var pos = {
    lat: 42.1,
    lng: -74.1
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 42,
      lng: -74
    },
    zoom: 6
  });

  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      pos.lat = position.coords.latitude;
      pos.lng = position.coords.longitude;

      map.setCenter(pos);
      var marker = new google.maps.Marker({
        position: pos,
        map: map,
        title: 'Release Source'
      });
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter(), map);
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter(), map);
  }

  function handleLocationError(input, infoWindow, center, map) {
    infoWindow.setContent("ERROR: " + input);
    infoWindow.setPosition(center);
    infoWindow.open(map);
  }
}
google.maps.event.addDomListener(window, 'load', initMap);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div id="map"></div>

proof of concept fiddle

这篇关于JavaScript Google Maps API如何将位置lat / long存储到全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆