Android Open Source - android-utils Location Utils






From Project

Back to project page android-utils.

License

The source code is released under:

Apache License

If you think the Android project android-utils listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 * Copyright 2014 Zhenguo Jin (jingle1267@163.com)
 *//  w w  w.  j  a v  a2 s .  c o m
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.worthed.util;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;
import android.util.Log;

/**
 * ?????????????????????????????????????
 *
 * @author jingle1267@163.com
 */
public class LocationUtils {

    private final static boolean DEBUG = true;
    private final static String TAG = "LocationUtils";

    /**
     * ???????????????????
     *
     * @param address ????????
     * @return ??????
     */
    public static double[] getLocationInfo(String address) {
        if (TextUtils.isEmpty(address)) {
            return null;
        }
        if (DEBUG) {
            LogUtils.d(TAG, "address : " + address);
        }
        // ????HttpClient???????????????????
        HttpClient client = new DefaultHttpClient();
        // ??????????????GET??
        HttpGet httpGet = new HttpGet("http://maps.google."
                + "com/maps/api/geocode/json?address=" + address
                + "ka&sensor=false");
        StringBuilder sb = new StringBuilder();
        try {
            // ????????????
            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            // ????????????????
            InputStream stream = entity.getContent();
            int b;
            // ?????????????
            while ((b = stream.read()) != -1) {
                sb.append((char) b);
            }
            // ????????????????JSONObject??
            JSONObject jsonObject = new JSONObject(sb.toString());
            // ?JSONObject?????????????location??
            JSONObject location = jsonObject.getJSONArray("results")
                    .getJSONObject(0).getJSONObject("geometry")
                    .getJSONObject("location");
            // ???????????
            double longitude = location.getDouble("lng");
            // ??????????
            double latitude = location.getDouble("lat");
            if (DEBUG) {
                LogUtils.d(TAG, "location : (" + longitude + "," + latitude + ")");
            }
            // ???????????????double[]??
            return new double[]{longitude, latitude};
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ???????????????????
     *
     * @param longitude ???
     * @param latitude  ??
     * @param lang      ?? ????????en
     * @return ????????
     * @throws Exception
     */
    public static String getAddress(double longitude, double latitude,
                                    String lang) throws Exception {
        if (DEBUG) {
            LogUtils.d(TAG, "location : (" + longitude + "," + latitude + ")");
        }
        if (lang == null) {
            lang = "en";
        }
        // ?????????
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
        HttpConnectionParams.setSoTimeout(params, 10 * 1000);
        // ????HttpClient???????????????????
        HttpClient client = new DefaultHttpClient(params);
        // ??????????????GET??
        HttpGet httpGet = new HttpGet("https://maps.googleapis.com/maps/api/"
                + "geocode/json?latlng=" + latitude + "," + longitude
                + "&sensor=false&language=" + lang);
        if (DEBUG) {
            LogUtils.d(TAG,
                    "URL : " + httpGet.getURI());
        }
        StringBuilder sb = new StringBuilder();
        // ????
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        // ???????????????
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            sb.append((char) b);
        }
        // ????????????????JSONObject
        JSONObject jsonObj = new JSONObject(sb.toString());
        Log.d("ConvertUtil", "getAddress:" + sb.toString());
        // ???????????????????
        JSONObject addressObject = jsonObj.getJSONArray("results")
                .getJSONObject(0);
        String address = decodeLocationName(addressObject);
        if (DEBUG) {
            LogUtils.d(TAG, "address : " + address);
        }
        return address;
    }

    /**
     * ????Google API ?????????????
     * https://developers.google.com/maps/documentation/geocoding
     *
     * @param jsonObject ????Json??
     * @return ???????
     */
    public static String decodeLocationName(JSONObject jsonObject) {
        JSONArray jsonArray;
        String country = "", city = "";
        String TYPE_COUNTRY = "country";
        String TYPE_LOCALITY = "locality";
        String TYPE_POLITICAL = "political";
        boolean hasCountry = false;
        try {
            jsonArray = jsonObject.getJSONArray("address_components");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jo = jsonArray.getJSONObject(i);
                JSONArray types = jo.getJSONArray("types");
                boolean hasLocality = false, hasPolicical = false;

                for (int j = 0; j < types.length(); j++) {
                    String type = types.getString(j);
                    if (type.equals(TYPE_COUNTRY) && !hasCountry) {
                        country = jo.getString("long_name");
                    } else {
                        if (type.equals(TYPE_POLITICAL)) {
                            hasPolicical = true;
                        }
                        if (type.equals(TYPE_LOCALITY)) {
                            hasLocality = true;
                        }
                        if (hasPolicical && hasLocality) {
                            city = jo.getString("long_name");
                        }
                    }
                }
            }
            return city + "," + country;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (jsonObject.has("formatted_address")) {
            try {
                return jsonObject.getString("formatted_address");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}




Java Source Code List

com.worthed.BuildConfig.java
com.worthed.app.BaseApplication.java
com.worthed.app.BaseCrashHandler.java
com.worthed.app.RebootThreadExceptionHandler.java
com.worthed.app.StartAppReceiver.java
com.worthed.demo.BitmapActivity.java
com.worthed.demo.MainActivity.java
com.worthed.demo.ViewFinderActivity.java
com.worthed.util.AnimationUtils.java
com.worthed.util.AppUtils.java
com.worthed.util.AssetDatabaseOpenHelper.java
com.worthed.util.BitmapUtil.java
com.worthed.util.CipherUtils.java
com.worthed.util.Colors.java
com.worthed.util.CommonUtil.java
com.worthed.util.DataCleanManager.java
com.worthed.util.DatabaseExportUtils.java
com.worthed.util.DateUtils.java
com.worthed.util.DeviceStatusUtils.java
com.worthed.util.DisplayUtils.java
com.worthed.util.DoubleKeyValueMap.java
com.worthed.util.DownloadManagerPro.java
com.worthed.util.FileUtils.java
com.worthed.util.HanziToPinyin.java
com.worthed.util.ImsiUtil.java
com.worthed.util.LocationUtils.java
com.worthed.util.LogUtils.java
com.worthed.util.NetUtil.java
com.worthed.util.PackageUtils.java
com.worthed.util.PhoneUtil.java
com.worthed.util.PollingUtils.java
com.worthed.util.PreferencesCookieStore.java
com.worthed.util.RUtils.java
com.worthed.util.RandomUtils.java
com.worthed.util.RegUtils.java
com.worthed.util.ResourceUtils.java
com.worthed.util.SDCardUtils.java
com.worthed.util.SettingUtils.java
com.worthed.util.ShellUtils.java
com.worthed.util.ShortCutUtils.java
com.worthed.util.Singleton.java
com.worthed.util.StringUtils.java
com.worthed.util.ViewAnimationUtils.java
com.worthed.util.ViewFinder.java
com.worthed.util.ViewUtils.java
com.worthed.util.WindowUtils.java