我把这个获取经纬度的类分享出来的原因:
1、我说了android手机获取本地GPS的经纬度有些手机不一定有值;他一直坚信google可以拿到;为什么就获取不到值;一直说让我就研究google定位的源代码;我反驳的理由:如果google没有对经纬度获取做了特别处理,为什么要开一个获取经纬度方法而不用android自带的jar方法,包括百度,高德也是一样;如果说本地API可以百分百获取到以及非常精确,这些第三方又不傻,他们就直接开启一个通过经纬度获取城市信息API即可,何必多开一个定位获取经纬度功能,多此一举;而且google的源代码等您看完,黄花菜都凉了
2、本来这个APP就是给国外用的,使用google获取经纬度就是免费的;硬要用获取本地GPS
3、在中国使用google获取经纬度慢,这个锅丢给前台;我在国外使用都是非常快;、
4、真的很无语,无法与架构师沟通;也许我菜吧
package com.xinyi.morefun.morefun.location;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
import com.xinyi.morefun.library.kallehttp.HttpManager;
import com.xinyi.morefun.library.kallehttp.httpInterface.HttpListener;
import com.xinyi.morefun.library.model.GoogleLocationModel;
import com.xinyi.morefun.library.util.JsonUtil;
import com.xinyi.morefun.library.util.LogUtil;
import com.xinyi.morefun.library.util2.BugUtil;
import com.xinyi.morefun.library.util2.StringUtil;
import com.xinyi.morefun.morefun.AppUserInfo;
import com.xinyi.morefun.morefun.http2.HttpConfig;
import com.xinyi.morefun.morefun.http2.HttpParamUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GoogleLocationManager implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private static volatile GoogleLocationManager googleLocationManager;
private GoogleApiClient mGoogleApiClient;
private LocationRequest locationRequest;
private Context context;
private String lng;
private String lat;
private OnGoogleLocationListener onGoogleLocationListener;
private GoogleLocationManager() {
}
public static GoogleLocationManager getInstanceFor() {
if (null == googleLocationManager) {
synchronized (GoogleLocationManager.class) {
if (googleLocationManager == null) {
googleLocationManager = new GoogleLocationManager();
}
}
}
return googleLocationManager;
}
/**
* 是否支持Google服务
* @return
*/
public boolean isGooglePlayServiceAvailable() {
int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (status == ConnectionResult.SUCCESS) {
return true;
} else {
return false;
}
}
/**
* 本地定位,优先本地定位,然后谷歌;谷歌定位慢也关前台事情,真的很无语;前台永远背锅,加速转后台中
* @param
* @param onGoogleLocationListener
*/
public void googleLocation(Context mContext, OnGoogleLocationListener onGoogleLocationListener) {
this.context = mContext;
this.onGoogleLocationListener = onGoogleLocationListener;
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
Location location=locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
if(location==null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location!=null){
lng = location.getLongitude() + "";
lat = location.getLatitude() + "";
LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
if(isRequestLocation()){
onGoogleLocationListener.onGoogleLocationFailCallback("本地定位失败, 错误信息:");
}
}else{
LogUtil.getInstanceFor().e("本地定位失败");
//别问我为啥加这个,如果遍历都拿不到经纬度;也别找我,测试得知还是有设备得不到经纬度;懒得解释;
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (location == null || l.getAccuracy() < location.getAccuracy()) {
// Found best last known location: %s", l);
location = l;
}
}
if(location==null){
googleLocation2(context,onGoogleLocationListener);
}else{
LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
if(isRequestLocation()){
onGoogleLocationListener.onGoogleLocationFailCallback("本地定位失败, 错误信息:");
}
}
}
}catch (Exception e){
LogUtil.getInstanceFor().e(""+e.getMessage());
onGoogleLocationListener.onGoogleLocationFailCallback("本地定位失败, 错误信息:");
}
}
/**
*
* @param mContext
* @param onGoogleLocationListener
* cityInfos[0] = addressComponentsBean.getLong_name();
* cityInfos[1] = resultsBean.getFormatted_address();
* cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
* cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
*/
public void googleLocation2(Context mContext, OnGoogleLocationListener onGoogleLocationListener) {
this.context = mContext;
this.onGoogleLocationListener = onGoogleLocationListener;
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
LogUtil.getInstanceFor().e("google position res");
// return;
}
LogUtil.getInstanceFor().e("google position");
mGoogleApiClient = new GoogleApiClient
.Builder(context)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addApi(LocationServices.API)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
mGoogleApiClient.connect();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
Status status = result.getStatus();
LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LogUtil.getInstanceFor().e("定位开启:SUCCESS: ");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
(Activity) context, 999);
LogUtil.getInstanceFor().e("定位开启:RESOLUTION_REQUIRED: ");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
LogUtil.getInstanceFor().e(location.getLatitude() + " onLocationChanged");
lat = location.getLatitude() + "";
lng = location.getLongitude() + "";
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
}
});
} catch (Exception e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
LogUtil.getInstanceFor().e("定位:SETTINGS_CAANCE_UNAVALABLE:");
break;
}
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
LogUtil.getInstanceFor().e("定位失败,谷歌连接失败,错误码:" );
BugUtil.getInstanceFor().saveOtherErrorMsg("定位失败,谷歌连接失败,错误码:" + connectionResult.getErrorCode() + " , 错误信息:" + connectionResult.getErrorMessage());
// onGoogleLocationListener.onGoogleLocationFailCallback("定位连接成功,但是谷歌没有给出数据");
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
Location location=locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
if(location==null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location==null){
location=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
if(location!=null){
lng = location.getLongitude() + "";
lat = location.getLatitude() + "";
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
}else{
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (location == null || l.getAccuracy() < location.getAccuracy()) {
// Found best last known location: %s", l);
location = l;
}
}
if(location!=null){
lng = location.getLongitude() + "";
lat = location.getLatitude() + "";
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
}
}
}catch (Exception e){
LogUtil.getInstanceFor().e(""+e.getMessage());
}
if(isRequestLocation()){
onGoogleLocationListener.onGoogleLocationFailCallback("定位失败,谷歌连接失败,错误码:" + connectionResult.getErrorCode() + " , 错误信息:" + connectionResult.getErrorMessage());
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LogUtil.getInstanceFor().e("onConnected google");
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
@Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
if (likelyPlaces != null && likelyPlaces.getCount() != 0) {//placeLikelihood.getLikelihood()越大越接近您的位置
//您要进行的业务操作
lng = likelyPlaces.get(0).getPlace().getLatLng().longitude + "";
lat = likelyPlaces.get(0).getPlace().getLatLng().latitude + "";
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
getPHPLocationResult(context,lat,lng,onGoogleLocationListener);
} else {//定位失败
LogUtil.getInstanceFor().e("定位连接成功,但是谷歌没有给出数据");
BugUtil.getInstanceFor().saveOtherErrorMsg("定位连接成功,但是谷歌没有给出数据");
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
Location location=locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
if(location==null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location==null){
location=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
if(location!=null){
lng = location.getLongitude() + "";
lat = location.getLatitude() + "";
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
}else{
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (location == null || l.getAccuracy() < location.getAccuracy()) {
// Found best last known location: %s", l);
location = l;
}
}
if(location!=null){
lng = location.getLongitude() + "";
lat = location.getLatitude() + "";
AppUserInfo.getInstanceFor().saveLat(lat);
AppUserInfo.getInstanceFor().saveLng(lng);
LogUtil.getInstanceFor().e("本地经纬度:"+lng+" , "+lat);
}
}
}catch (Exception e){
LogUtil.getInstanceFor().e(""+e.getMessage());
}
if(isRequestLocation()){
onGoogleLocationListener.onGoogleLocationFailCallback("定位连接成功,但是谷歌没有给出数据");
}
}
}
});
}
public boolean isRequestLocation(){
if(!StringUtil.getInstanceFor().isEmpty(AppUserInfo.getInstanceFor().getLat())&&!StringUtil.getInstanceFor().isEmpty(AppUserInfo.getInstanceFor().getLng())){
if(AppUserInfo.getInstanceFor().getLat().length()<4&&AppUserInfo.getInstanceFor().getLng().length()<4){
return true;
}
getPHPLocationResult(context,AppUserInfo.getInstanceFor().getLat(),AppUserInfo.getInstanceFor().getLng(),onGoogleLocationListener);
return false;
}
return true;
}
@Override
public void onConnectionSuspended(int i) {
LogUtil.getInstanceFor().e("onConnectionSuspended: "+i);
}
/**
* 获取城市信息
* @param context 上下文
* @param latlng 经纬度 中间要用逗号分割
* @param onGoogleLocationListener 回调接口
*/
public void getLocationResult(Context context, final String latlng, final OnGoogleLocationListener onGoogleLocationListener){
Map<String,Object> params = new HashMap<>();
params.put("latlng",latlng);
params.put("key","您的googlekey");
params.put("language","en-us");
HttpManager.getInstanceFor(context).httpGetAPI(HttpConfig.GOOGLEBYCITY, params, new HttpListener() {
@Override
public void onHttpResult(Object data,String msg) {
String[] str = getJsonToCityInfoLocality((String) data);
if(str!=null){
LogUtil.getInstanceFor().e("定位成功:"+str[0]);
AppUserInfo.getInstanceFor().savaCity(str[0]);
onGoogleLocationListener.onGoogleLocationSuccessCallback(str[0],str[1],str[2],str[3]);
}else{//定位失败
BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌给的JSON无法找到地址信息"+latlng);
onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌给的JSON无法找到地址信息");
}
}
@Override
public void onHttpFail(String code, String msg) {//不会执行
}
@Override
public void onHttpError(String errormsg) {//定位失败
LogUtil.getInstanceFor().e("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
}
},null);
}
// cityInfos[0] = addressComponentsBean.getLong_name();
// cityInfos[1] = resultsBean.getFormatted_address();
// cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
// cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
/**
* PHP通过经纬度获取城市名
* @param onGoogleLocationListener
*/
public void getPHPLocationResult(Context mContext,String lat,String lng,OnGoogleLocationListener onGoogleLocationListener) {
this.context = mContext;
Map<String,Object> params = new HashMap<>();
params.put("lat",lat);
params.put("lng",lng);
HttpManager.getInstanceFor(context).httpGetAPI(HttpConfig.GETCITYNAME, HttpParamUtil.getInstanceFor().postPHPValidationParam(params), new HttpListener() {
@Override
public void onHttpResult(Object data,String msg) {
if(data instanceof ApiLocationResult){
ApiLocationResult apiLocationResult = (ApiLocationResult) data;
onGoogleLocationListener.onGoogleLocationSuccessCallback(apiLocationResult.getCityname(),apiLocationResult.getFormatted_address(),lat,lng);
}else{
getLocationResult(context, lat+","+lng,onGoogleLocationListener);
}
}
@Override
public void onHttpFail(String code,String msg) {
getLocationResult(context, lat+","+lng,onGoogleLocationListener);
}
@Override
public void onHttpError(String errormsg) {
onGoogleLocationListener.onGoogleLocationFailCallback("PHP网络请求失败");
}
},ApiLocationResult.class);
}
public class ApiLocationResult{
/**
* cityname : Guangzhou Shi
*/
private String cityname;
private String formatted_address;
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
/**
* 计算两点的曲线距离以及时间
* @param slatlng 开始地点
* @param elatlng 结束地点
* @param onGoogleRouleListener 回调;第一个参数是距离m,第一个参数是时间s
*/
public void getRouteDistance(String slatlng, String elatlng, final OnGoogleRouleListener onGoogleRouleListener){
LogUtil.getInstanceFor().e("计算曲线距离");
Map<String,Object> params = new HashMap<>();
params.put("units","metric");
params.put("key","您的googlekey");
params.put("language","en-us");
params.put("origins",slatlng);
params.put("destinations",elatlng);
HttpManager.getInstanceFor(context).httpGetAPI(HttpConfig.GOOGLEQXJL, params, new HttpListener() {
@Override
public void onHttpResult(Object data,String msg) {
try{
RouteDistanceModel routeDistanceModel = (RouteDistanceModel) JsonUtil.getInstanceFor().parseObject((String) data,RouteDistanceModel.class);
if(StringUtil.getInstanceFor().equalsUL(routeDistanceModel.getStatus(),"OK")){
if(routeDistanceModel.getRows()!=null&&routeDistanceModel.getRows().size()!=0&&routeDistanceModel.getRows().get(0).getElements()!=null&&routeDistanceModel.getRows().get(0).getElements().size()!=0){
int distance = routeDistanceModel.getRows().get(0).getElements().get(0).getDistance().getValue();
int duration = routeDistanceModel.getRows().get(0).getElements().get(0).getDuration().getValue();
onGoogleRouleListener.onGoogleRouleSuccessCallback(distance,duration);
}else{
BugUtil.getInstanceFor().saveOtherErrorMsg("请求计算距离接口成功,但是谷歌没有给数据"+data);
onGoogleRouleListener.onGoogleRouleFailCallback("请求计算距离接口成功,但是谷歌没有给数据");
}
}else{
BugUtil.getInstanceFor().saveOtherErrorMsg("请求计算距离接口成功,但是谷歌给的数据是失败的"+data);
onGoogleRouleListener.onGoogleRouleFailCallback("请求计算距离接口成功,但是谷歌给的数据是失败的");
}
}catch (Exception e){
BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌获取城市信息的接口请求失败"+e.getMessage());
onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌获取城市信息的接口请求失败"+e.getMessage());
}
}
@Override
public void onHttpFail(String code, String msg) {//不会执行
}
@Override
public void onHttpError(String errormsg) {//定位失败
BugUtil.getInstanceFor().saveOtherErrorMsg("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
onGoogleLocationListener.onGoogleLocationFailCallback("定位成功,但是谷歌获取城市信息的接口请求失败"+errormsg);
}
},null);
}
// /**
// * 获取谷歌城市信息 0 城市名 1 详细地址 2 纬度 3 经度
// * @param json
// * @return
// */
// @Deprecated
// private String[] getJsonToCityInfo(String json){
// String[] cityInfos = new String[4];
// GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
// if(googleLocationModel == null){
// return null;
// }else{
// if(googleLocationModel.getStatus().equals("OK")){
// for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
// for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
// for(String type:addressComponentsBean.getTypes()){
// if(type.equals("locality")){
// cityInfos[0] = addressComponentsBean.getLong_name();
// cityInfos[1] = resultsBean.getFormatted_address();
// cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
// cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
// return cityInfos;
// }else if(type.equals("administrative_area_level_2")){
// cityInfos[0] = addressComponentsBean.getLong_name();
// cityInfos[1] = resultsBean.getFormatted_address();
// cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
// cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
// return cityInfos;
// }else if(type.equals("administrative_area_level_1")){
// cityInfos[0] = addressComponentsBean.getLong_name();
// cityInfos[1] = resultsBean.getFormatted_address();
// cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
// cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
// return cityInfos;
// }
// }
// }
// }
// }
// }
// return null;
// }
private String[] getJsonToCityInfoAdministrative_area_level_1(String json){
String[] cityInfos = new String[4];
GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
if(googleLocationModel == null){
return null;
}else{
if(googleLocationModel.getStatus().equals("OK")){
for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
for(String type:addressComponentsBean.getTypes()){
if(type.equals("administrative_area_level_1")){
cityInfos[0] = addressComponentsBean.getLong_name();
cityInfos[1] = resultsBean.getFormatted_address();
cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
return cityInfos;
}
}
}
}
}
}
return null;
}
private String[] getJsonToCityInfoAdministrative_area_level_2(String json){
String[] cityInfos = new String[4];
GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
if(googleLocationModel == null){
return null;
}else{
if(googleLocationModel.getStatus().equals("OK")){
for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
for(String type:addressComponentsBean.getTypes()){
if(type.equals("administrative_area_level_2")){
cityInfos[0] = addressComponentsBean.getLong_name();
cityInfos[1] = resultsBean.getFormatted_address();
cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
return cityInfos;
}else{
getJsonToCityInfoAdministrative_area_level_1(json);
break;
}
}
}
}
}
}
return null;
}
private String[] getJsonToCityInfoLocality(String json){
String[] cityInfos = new String[4];
GoogleLocationModel googleLocationModel = (GoogleLocationModel) JsonUtil.getInstanceFor().parseObject(json,GoogleLocationModel.class);
if(googleLocationModel == null){
return null;
}else{
if(googleLocationModel.getStatus().equals("OK")){
for (GoogleLocationModel.ResultsBean resultsBean:googleLocationModel.getResults()){
for(GoogleLocationModel.ResultsBean.AddressComponentsBean addressComponentsBean:resultsBean.getAddress_components()){
for(String type:addressComponentsBean.getTypes()){
if(type.equals("locality")){
cityInfos[0] = addressComponentsBean.getLong_name();
cityInfos[1] = resultsBean.getFormatted_address();
cityInfos[2] = resultsBean.getGeometry().getLocation().getLat()+"";
cityInfos[3] = resultsBean.getGeometry().getLocation().getLng()+"";
return cityInfos;
}else{
getJsonToCityInfoAdministrative_area_level_2(json);
break;
}
}
}
}
}
}
return null;
}
public interface OnGoogleLocationListener{
void onGoogleLocationSuccessCallback(String... cityInfo);
void onGoogleLocationFailCallback(String... errorMsg);
}
public interface OnGoogleRouleListener{
void onGoogleRouleSuccessCallback(Object... rouleInfo);
void onGoogleRouleFailCallback(String... errorMsg);
}
}