天天看點

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

高德定位 官方文檔: https://lbs.amap.com/api/android-location-sdk/locationsummary/

高德定位 SDK 下載下傳位址

cocosCreator 基于2.1.4版本

準備工作

高德開發者平台

1.登陸賬号 》進入控制台 》應用管理 》 我的應用

2.建立新應用

3.配置Android iOS 擷取高德key值

Android配置

安全碼SHA1的擷取

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

ios配置

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

Android層

1.導入高德定位SDK

cocosCreator - 高德定位接入準備工作Android層iOS層前端js
  1. AndroidManifest.xml 修改
    cocosCreator - 高德定位接入準備工作Android層iOS層前端js
引入需要的權限
<!--用于進行網絡定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!--用于通路GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!--用于擷取營運商資訊,用于支援提供營運商資訊相關的接口-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!--用于通路wifi網絡資訊,wifi資訊會用于進行網絡定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!--用于擷取wifi的擷取權限,wifi資訊會用來進行網絡定位-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!--用于通路網絡,網絡定位需要上網-->
    <uses-permission android:name="android.permission.INTERNET" />
    <!--用于讀取手機目前的狀态-->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!--用于寫入緩存資料到擴充存儲卡-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!--用于申請調用A-GPS子產品-->
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <!--用于申請擷取藍牙資訊進行室内定位-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
           
<!-- 定位sdk需要配置 -->
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="在高德平台申請的Key值" />
           

3.導入代碼

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

gpsContr.java

package org.cocos2dx.javascript.gps;

import android.Manifest;
import android.content.Context;
import android.support.v4.content.PermissionChecker;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;

public class gpsContr {
    private static boolean isLocationReturn = false;
    private static AMapLocationClientOption locationOption = null;
    private static AMapLocationClient locationClient = null;
    private static CoordinateConverter converter = null;

    private static float longitude = -1;
    private static float latitude = -1;
    private static String city = "";
    private static String address = "";
    private static String district = "";
    private static String poiName = "";
    private static String province = "";
    private static String GPSStatus = ""; // ..GPS 定位得狀态

    private static String locationResult = "";
    private static Context m_context = null;

    public static void GPSInit(Context context) {
        isGPSReady();
        m_context = context;
        initLocation();
    }

    // 初始化定位
    private static void initLocation() {
        // 初始化client
        locationClient = new AMapLocationClient(m_context);
        locationOption = getDefaultOption();
        // 設定定位參數
        locationClient.setLocationOption(locationOption);
        // 設定定位監聽
        locationClient.setLocationListener(locationListener);
        // 計算距離需要
        converter = new CoordinateConverter(m_context);
    }
    // 銷毀定位
    public static void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在目前Activity執行個體化的,
             * 在Activity的onDestroy中一定要執行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
            converter = null;
        }
    }

    // 預設的定位參數
    private static AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);// 可選,設定定位模式,可選的模式有高精度、僅裝置、僅網絡。預設為高精度模式
        // AMapLocationMode.Battery_Saving
        mOption.setGpsFirst(false);// 可選,設定是否gps優先,隻在高精度模式下有效。預設關閉
        mOption.setHttpTimeOut(30000);// 可選,設定網絡請求逾時時間。預設為30秒。在僅裝置模式下無效
        mOption.setInterval(300000);// 可選,設定定位間隔。預設為2秒 設定成5分鐘定位一次
        mOption.setNeedAddress(true);// 可選,設定是否傳回逆地理位址資訊。預設是true
        mOption.setOnceLocation(false);// 可選,設定是否單次定位。預設是false
        mOption.setOnceLocationLatest(false);// 可選,設定是否等待wifi重新整理,預設為false.如果設定為true,會自動變為單次定位,持續定位時不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);// 可選, 設定網絡請求的協定。可選HTTP或者HTTPS。預設為HTTP
        mOption.setSensorEnable(false);// 可選,設定是否使用傳感器。預設是false
        mOption.setWifiScan(true); // 可選,設定是否開啟wifi掃描。預設為true,如果設定為false會同時停止主動重新整理,停止以後完全依賴于系統重新整理,定位位置可能存在誤差
        mOption.setLocationCacheEnable(true); // 可選,設定是否使用緩存定位,預設為true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);// 可選,設定逆地理資訊的語言,預設值為預設語言(根據所在地區選擇語言)
        return mOption;
    }

    private static void isGPSReady() {
        try {
            int versionOne = PermissionChecker.checkSelfPermission(m_context, Manifest.permission.ACCESS_FINE_LOCATION);
            if (versionOne != 0) {
//                LocationManager locationManager;
//                locationManager = (LocationManager) m_context.getSystemService(Context.LOCATION_SERVICE);
                List<String> providers = locationManager.getProviders(true);
//                String locationProvider = null;
//                if (providers.contains(LocationManager.GPS_PROVIDER)) {
//                    // 如果是GPS
//                    locationProvider = LocationManager.GPS_PROVIDER;
//                } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//                    // 如果是Network
//                    locationProvider = LocationManager.NETWORK_PROVIDER;
//                }
                versionOne = PermissionChecker.checkSelfPermission(m_context, Manifest.permission.ACCESS_FINE_LOCATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 定位監聽
    private static AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuilder sb = new StringBuilder();
                // errCode等于0代表定位成功,其他的為定位失敗,具體的可以參照官網定位錯誤碼說明
                int errCode = location.getErrorCode();
                if (errCode == 0) {
                    sb.append("定位成功" + "\n");
                    sb.append("定位類型: " + location.getLocationType() + "\n");
                    sb.append("經    度    : " + location.getLongitude() + "\n");
                    sb.append("緯    度    : " + location.getLatitude() + "\n");
                    sb.append("精 度 : " + location.getAccuracy() + "米" + "\n");
                    sb.append("省 : " + location.getProvince() + "\n");
                    sb.append("市 : " + location.getCity() + "\n");
                    sb.append("區 : " + location.getDistrict() + "\n");
                    sb.append("地 址 : " + location.getAddress() + "\n");
                    sb.append("興趣點 : " + location.getPoiName() + "\n");
                    isLocationReturn = true;
                    GPSStatus = "";
                    longitude = (float) location.getLongitude();
                    latitude = (float) location.getLatitude();
                    city = location.getCity();
                    address = location.getAddress();
                    district = location.getDistrict();
                    poiName = location.getPoiName();
                    province = location.getProvince();
                } else if (errCode == 12) {
                    GPSStatus = "沒有開啟App的定位權限";
                } else if (errCode == 14) {
                    GPSStatus = "GPS定位失敗";
                } else {
                    GPSStatus = "GPS信号差";
                    // 定位失敗
                    sb.append("定位失敗" + "\n");
                    sb.append("錯誤碼:" + location.getErrorCode() + "\n");
                    sb.append("錯誤資訊:" + location.getErrorInfo() + "\n");
                    sb.append("錯誤描述:" + location.getLocationDetail() + "\n");
                    isLocationReturn = true;
                }
                locationResult = sb.toString();
            }

            // "定位失敗"

        }
    };

    // 開始定位
    public static void startLocation() {
        // 啟動定位
        locationClient.startLocation();
    }

    // 停止定位
    public static void stopLocation() {
        locationClient.stopLocation();
        locationResult = "stop location";
    }

    // 擷取定位的結果字元串
    public static String getLocationString() {
        if (isLocationReturn) {
            isLocationReturn = false;
            return locationResult;
        } else {
            return "定位資訊還未傳回";
        }
    }

    public static float getLongitude() {
        return longitude;
    }

    public static float getLatitude() {
        return latitude;
    }

    // 省
    public static String getProvince() {
        return province;
    }

    // 市
    public static String getCity() {
        return city;
    }

    // 區
    public static String getDistrict() {
        return district;
    }

    // 位址
    public static String getAddress() {
        return address;
    }

    // 興趣點
    public static String getPoiName() {
        return poiName;
    }

    // 定位得狀态 自己定義得
    public static String getGpsStatus() {
        return GPSStatus;
    }
}

           

AppActivity.java中調用即可

import org.cocos2dx.javascript.gps.gpsContr;//引入腳本
 gpsContr.GPSInit(this);  //在onCreate()方法中初始化定位
 gpsContr.destroyLocation(); //在onDestroy()方法中銷毀定位
           

iOS層

1.引入iOS需要的SDK

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

2.開啟Background Modes --> Location updates

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

3.配置info.plist

定位需要的權限
cocosCreator - 高德定位接入準備工作Android層iOS層前端js

<key>NSBluetoothPeripheralUsageDescription</key> <string>是否許允此App使用藍牙?</string> <key>NSCalendarsUsageDescription</key> <string>是否允許此App使用月曆?</string> <key>NSCameraUsageDescription</key> <string>是否允許此App使用您的相機?</string> <key>NSContactsUsageDescription</key> <string>是否允許此App通路您的通訊錄?</string> <key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>我們想要通路您的位置</string> <key>NSLocationAlwaysUsageDescription</key> <string>我們想要通路您的位置</string> <key>NSLocationWhenInUseUsageDescription</key> <string>我們想要通路您的位置</string> <key>NSMicrophoneUsageDescription</key> <string>允許我通路麥克風才能錄音哦</string> <key>NSPhotoLibraryUsageDescription</key> <string>是否允許此App通路您的相冊?</string>

4.引入需要的系統庫

CoreLocation.framework //新增的

cocosCreator - 高德定位接入準備工作Android層iOS層前端js

5.調用方法

AppController.h

cocosCreator - 高德定位接入準備工作Android層iOS層前端js
#import <UIKit/UIKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

@class RootViewController;

@interface AppController : NSObject <UIApplicationDelegate,WXApiDelegate>
{
}

@property(nonatomic, readonly) RootViewController* viewController;
@property (nonatomic, strong) AMapLocationManager* locationManager;

@end
           

AppController.mm

/****************************************************************************
 Copyright (c) 2010-2013 cocos2d-x.org
 Copyright (c) 2013-2016 Chukong Technologies Inc.
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
 http://www.cocos2d-x.org
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#import "AppController.h"
#import "cocos2d.h"
#import "AppDelegate.h"

#import "RootViewController.h"
#import "SDKWrapper.h"
#import "platform/ios/CCEAGLView-ios.h"

#import "MessageViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

#define APP_NAME    @"hs_jindian13s"
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
static void SendToJS(const char* str){
    se::ScriptEngine::getInstance()->evalString(str);
}

using namespace cocos2d;

@interface AppController ()<AMapLocationManagerDelegate>

@end

@implementation AppController
Application* app = nullptr;
static float latitude = -1;
static float longgitude = -1;
static NSString *city = @"";
@synthesize window;

#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[SDKWrapper getInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    // Add the view controller's view to the window and display.
    float scale = [[UIScreen mainScreen] scale];
    CGRect bounds = [[UIScreen mainScreen] bounds];
    window = [[UIWindow alloc] initWithFrame: bounds];
    
    // cocos2d application instance
    app = new AppDelegate(bounds.size.width * scale, bounds.size.height * scale);
    app->setMultitouch(true);
    // Use RootViewController to manage CCEAGLView
    _viewController = [[RootViewController alloc]init];
    
#ifdef NSFoundationVersionNumber_iOS_7_0
    _viewController.automaticallyAdjustsScrollViewInsets = NO;
    _viewController.extendedLayoutIncludesOpaqueBars = NO;
    _viewController.edgesForExtendedLayout = UIRectEdgeAll;
#else
    _viewController.wantsFullScreenLayout = YES;
#endif
    MessageViewController* Voiceview = [[MessageViewController alloc] init];
    [_viewController.view addSubview:Voiceview.view];
    // Set RootViewController to window
    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0){
        // warning: addSubView doesn't work on iOS6
        [window addSubview: _viewController.view];
    }else{
        // use this method on ios6
        [window setRootViewController:_viewController];
    }
    [window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    //run the cocos2d-x game scene
    app->start();
    [AMapServices sharedServices].apiKey =@"高德key";
    
    [self configLocationManager];
    [self startLocation];
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    [[SDKWrapper getInstance] applicationWillResignActive:application];
   
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    [[SDKWrapper getInstance] applicationDidBecomeActive:application];
   
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    [[SDKWrapper getInstance] applicationDidEnterBackground:application];
    app->applicationDidEnterBackground();
     
}

- (void)applicationWillEnterForeground:(UIApplication *)application {

    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    [[SDKWrapper getInstance] applicationWillEnterForeground:application];
    app->applicationWillEnterForeground();
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[SDKWrapper getInstance] applicationWillTerminate:application];
    delete app;
    app = nil;
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

#pragma location
- (void)configLocationManager {
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    
    //設定不允許系統暫停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //設定允許在背景定位
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
    //設定允許連續定位逆地理
    [self.locationManager setLocatingWithReGeocode:YES];
    
    //設定定位最小更新距離方法如下,機關米。當兩次定位距離滿足設定的最小更新距離時,SDK會傳回符合要求的定位結果
    [self.locationManager setDistanceFilter:200];
}

- (void) startLocation {
    [self.locationManager startUpdatingLocation];
}

- (void)cleanUpAction {
    //停止定位
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    //    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    latitude = location.coordinate.latitude;
    longgitude = location.coordinate.longitude;
    city = reGeocode.city;
    NSLog(@"lat:%f;lon:%f; city : %@", latitude, longgitude, city);
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
}

//緯度
+ (float) getLatitude {
    return latitude;
}

//經度
+ (float) getLonggitude {
    return longgitude;
}

//市
+ (NSString*) getCity {
    return city;
}
@end

           

前端js

sendLocation() {
    	let Longgitude= ''; //經度
        let Latitude= '';   //緯度
        if (cc.sys.OS_ANDROID === cc.sys.os) {
            Latitude= jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getLatitude", "()Ljava/lang/String;");
            Longgitude= jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getLongitude", "()Ljava/lang/String;");
        } else if (cc.sys.OS_IOS === cc.sys.os) {
            Latitude = jsb.reflection.callStaticMethod("AppController", "getLatitude"); 
            Longgitude= jsb.reflection.callStaticMethod("AppController", "getLonggitude");
        }
    },
           

繼續閱讀