jquery - 检索最后已知的地理位置 - Phonegap

标签 jquery android iphone html geolocation

以下代码

navigator.geolocation.getCurrentPosition(getGeo_Success, getGeo_Fail, {
    enableHighAccuracy : true,
    maximumAge : Infinity,
    timeout : 15000
});

检索当前 GPS 位置 - 但是 - 必须有有效的 GPS 信号(当然,设备的 GPS 功能应该打开)。

如果我们查看其他应用程序(例如 Android 设备上的 map ) - 它知道如何检索最后已知位置 - 即使我没有使用更新地理位置的应用程序打开 map 之前 - 它会在 map 上显示我的位置,即使我在根本没有 GPS 信号的建筑物内。

只是澄清一下:我对应用程序检索到的最后一个地理位置不感兴趣,因为下次我启动它时,该地理位置可能会无关紧要。

问题是:我们如何使用 HTML5/Phonegap 实现这一目标?似乎 navigator.geolocation 只知道检索当前位置,尽管 maximumAge 设置为 Infinity (这意味着,最后缓存的位置是无关紧要的,所以任何命中都可以(或者,应该是!))

最佳答案

Android 解决方案(iPhone 解决方案如下):

这很整洁:

我使用了 Android 的 native LocationManager,它提供了 getLastKnownLocation 函数 - 名称说明了一切

这是相关代码

1) 将以下 java 类添加到您的应用程序

package your.package.app.app;

import org.apache.cordova.DroidGap;

import android.content.Context;
import android.location.*;
import android.os.Bundle;
import android.webkit.WebView;

public class GetNativeLocation implements LocationListener {
    private WebView mAppView;
    private DroidGap mGap;
    private Location mostRecentLocation;

    public GetNativeLocation(DroidGap gap, WebView view) {
        mAppView = view;
        mGap = gap;
    }

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        getLocation();
    }

    public void getLocation() {
        LocationManager lm = 
                        (LocationManager)mGap.
                                        getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(criteria, true);

        lm.requestLocationUpdates(provider, 1000, 500, this);
        mostRecentLocation = lm
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }

    public void doInit(){
        getLocation();
    }

    public double getLat(){ return mostRecentLocation.getLatitude();}
    public double getLong() { return mostRecentLocation.getLongitude(); }
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub  
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub  
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

2) 确保您的主类如下所示:

public class App extends DroidGap {

    // Hold a private member of the class that calls LocationManager
    private GetNativeLocation gLocation;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // This line is important, as System Services are not available
        // prior to initialization
        super.init();

        gLocation = new GetNativeLocation(this, appView);

        // Add the interface so we can invoke the java functions from our .js 
        appView.addJavascriptInterface(gLocation, "NativeLocation");

        try {
            super.loadUrl("file:///android_asset/www/index.html");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }
}

3) 在您的 JS 代码中,只需使用以下方式调用 native java:

window.NativeLocation.doInit();
alert(window.NativeLocation.getLat());
alert(window.NativeLocation.getLong());

这就是大家! :-)

编辑: iPhone解决方案:

我编写了一个小型 Phonegap 插件,它创建了一个自定义类的接口(interface),该类利用 iOS 的 native CLLocationManager

1) Phonegap 插件(JS)

var NativeLocation = {
    doInit: function(types, success, fail) {
        return Cordova.exec(success, fail, "NativeLocation", "doInit", types);
    },

    getLongitude: function(types, success, fail){
        return Cordova.exec(success, fail, "NativeLocation", "getLongitude", types);
    },

    getLatitude: function(types, success, fail){
        return Cordova.exec(success, fail, "NativeLocation", "getLatitude", types);
    }
}

2) Objective-C 类使我们能够调用“CCLocationManager 的函数” *NativeLocation.h*

#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
#import <CoreLocation/CoreLocation.h>

@protocol NativeLocationDelegate
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;

@end

@interface NativeLocation : CDVPlugin <CLLocationManagerDelegate> {
    id delegate;
    NSString* callbackID;
    CLLocationManager *lm;
    Boolean bEnabled;
    double nLat;
    double nLon;
}

@property (nonatomic, copy) NSString* callbackID;
@property (nonatomic, retain) CLLocationManager *lm;
@property (nonatomic, readonly) Boolean bEnabled;
@property (nonatomic, assign) id delegate;

- (void) doInit:(NSMutableArray*)arguments
                                 withDict:(NSMutableDictionary*)options;
- (void) getLatitude:(NSMutableArray*)arguments 
                                 withDict:(NSMutableDictionary *)options;
- (void) getLongitude:(NSMutableArray*)arguments 
                                 withDict:(NSMutableDictionary *)options;

@end

NativeLocation.m

#import "NativeLocation.h"

@implementation NativeLocation

@synthesize callbackID;
@synthesize lm;
@synthesize bEnabled;
@synthesize delegate;

- (void)doInit:(NSMutableArray *)arguments 
                                 withDict:(NSMutableDictionary *)options{
    if (self != nil){
        self.lm = [[[CLLocationManager alloc] init] autorelease];
        self.lm.delegate = self;
        if (self.lm.locationServicesEnabled == NO)
            bEnabled = FALSE;
        else bEnabled = TRUE;
    }

    nLat = 0.0;
    nLon = 0.0;

    if (bEnabled == TRUE)
        [self.lm startUpdatingLocation];

    CDVPluginResult* pluginResult = [CDVPluginResult 
                                    resultWithStatus:CDVCommandStatus_OK 
                                    messageAsString[@"OK"
                                    stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    if (bEnabled == TRUE){
        [self writeJavascript: [pluginResult 
                               toSuccessCallbackString:self.callbackID]];
    } else {
        [self writeJavascript: [pluginResult 
                               toErrorCallbackString:self.callbackID]];
    }
}

- (void)locationManager:(CLLocationManager *)manager 
                        didUpdateToLocation:(CLLocation *)newLocation 
                        fromLocation:(CLLocation *)oldLocation {
    if ([self.delegate conformsToProtocol:@protocol(NativeLocationDelegate)])
        [self.delegate locationUpdate:newLocation ];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([self.delegate conformsToProtocol:@protocol(NativeLocationDelegate)])
        [self.delegate locationError:error];
}

- (void)dealloc {
    [self.lm release];
    [super dealloc];
}

- (void)locationUpdate:(CLLocation *)location {
    CLLocationCoordinate2D cCoord = [location coordinate];
    nLat = cCoord.latitude;
    nLon = cCoord.longitude;

}

- (void)getLatitude:(NSMutableArray *)arguments 
                                      withDict:(NSMutableDictionary *)options{

    self.callbackID = [arguments pop];

    nLat = lm.location.coordinate.latitude;
    nLon = lm.location.coordinate.longitude;

    CDVPluginResult* pluginResult = [CDVPluginResult 
                                    resultWithStatus:CDVCommandStatus_OK 
                                    messageAsDouble:nLat];

    [self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]];

}
- (void)getLongitude:(NSMutableArray *)arguments 
                                       withDict:(NSMutableDictionary *)options{

    self.callbackID = [arguments pop];

    nLat = lm.location.coordinate.latitude;
    nLon = lm.location.coordinate.longitude;

    CDVPluginResult* pluginResult = [CDVPluginResult 
                     resultWithStatus:CDVCommandStatus_OK messageAsDouble:nLon];

    [self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]];

}

@end

3) 最后,调用主 .js 中的所有内容

function getLongitudeSuccess(result){
    gLongitude = result;
}

function getLatitudeSuccess(result){
    gLatitude = result;
}

function runGPSTimer(){
    var sTmp = "gps";

    theTime = setTimeout('runGPSTimer()', 1000);

    NativeLocation.getLongitude(
                                ["getLongitude"],
                                getLongitudeSuccess,
                                function(error){ alert("error: " + error); }
                                );

    NativeLocation.getLatitude(
                               ["getLatitude"],
                               getLatitudeSuccess,
                               function(error){ alert("error: " + error); }
                               );

关于jquery - 检索最后已知的地理位置 - Phonegap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10897081/

相关文章:

Android清除webview线程,释放内存,避免OutOfMemoryError

android - Android 手机图标的开源版本

javascript - 更改源后视频闪烁一次

javascript - 动态添加html内容到页面

javascript - 通过 JS/jQuery 访问和操作 DOM 中的子元素

javascript - 是否可以将 modernizr 添加到 jsFiddle 并在 Chrome/firefox 中查看 css3 透视图

android - 为什么不同的设备有不同的 Action_mask 值

iphone - iOS 新窗口以应用程序模式打开

iphone - 按下按钮时切换到另一个 View

iphone - 通用应用程序的最小启动图像数