简体   繁体   English

ajax调用的经度和纬度-HTML5

[英]Latitude and Longitude for ajax call - Html5

I'm trying to get the user current latitude and longitude and use it on an ajax call. 我正在尝试获取用户当前的纬度和经度,并在ajax调用中使用它。 I have an array of cities and functions that get the users location, but somehow the variables are not getting any value. 我有一系列可以获取用户位置的城市和功能,但是不知何故变量没有任何价值。

Here is some code: 这是一些代码:

function getLng(){
navigator.geolocation.getCurrentPosition(lng, error);
}

 function getLat(){
navigator.geolocation.getCurrentPosition(lat, error);
}

function error(err){
console.warn('Error('+err.code+'):'+err.message);
}


function lat(position){
var crd = position.coords;
return crd.latitude;
}

 function lng(position){
  var crd = position.coords;
  return crd.longitude;
}

My object is like this: 我的对象是这样的:

 {
id:'currentLocation',
name:'Current Location',
lat: getLat(),
lng: getLng(),
lastUpdated: -1,
weatherData: null
}

And my ajax call is like this: function getWeatherDataForCityId(city){ 我的ajax调用是这样的:function getWeatherDataForCityId(city){

$.ajax({
url: 'https://api.forecast.io/forecast/<apikey>/' + city.lat +","+city.lng+"?units=si",
jsonp:'callback', 
dataType:'jsonp', 
success:function(data){
(stuff...)

I don't know why but the city.lat keep coming as 'undefined'. 我不知道为什么,但是city.lat一直以“未定义”的形式出现。

I'm allowing the browser to share my location.(I'm on firefox) 我允许浏览器共享我的位置。(我使用的是Firefox)

Can someone help? 有人可以帮忙吗?

This is how you need to use getCurrentPosition 这就是您需要使用getCurrentPosition的方式

function success(position) {
    $.ajax({
        url: 'https://api.forecast.io/forecast/<apikey>/' + position.coords.latitude + "," + position.coords.longitude + "?units=si",
        jsonp:'callback', 
        dataType:'jsonp', 
        success:function(data){
            (stuff...)
        }
    });
}

function failure() {
    console.warn('Error('+err.code+'):'+err.message);
}

navigator.geolocation.getCurrentPosition(success, failure);

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

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