Android 通過當前經緯度獲得城市的執行個體代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:package com.yy;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class GetCity {
/**
* 藉助Google MAP 通過使用者當前經緯度 獲得使用者當前城市
*/
static final String GOOGLE_MAPS_API_KEY = "abcdefg";

private LocationManager locationManager;
private Location currentLocation;
private String city="全國";
public GetCity(Context context) {
this.locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
//只是簡單的擷取城市 不需要即時更新 所以這裡先注釋
// this.locationManager.requestLocationUpdates(
// LocationManager.GPS_PROVIDER, 1000, 0,
// new LocationListener() {
// public void onLocationChanged(Location loc) {
// //當座標改變時觸發此函數,如果Provider傳進相同的座標,它就不會被觸發
// // Save the latest location
// currentLocation = loc;
// // Update the latitude & longitude TextViews
// System.out
// .println("getCity()"
// + (loc.getLatitude() + " " + loc
// .getLongitude()));
// }
//
// public void onProviderDisabled(String arg0) {
// System.out.println(".onProviderDisabled(關閉)"+arg0);
// }
//
// public void onProviderEnabled(String arg0) {
// System.out.println(".onProviderEnabled(開啟)"+arg0);
// }
//
// public void onStatusChanged(String arg0, int arg1,
// Bundle arg2) {
// System.out.println(".onStatusChanged(Provider的轉態在可用、" +
// "暫時不可用和無服務三個狀態直接切換時觸發此函數)"+
// arg0+" "+arg1+" "+arg2);
// }
// });
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (currentLocation == null)
currentLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
/**
* 開始解析
*/
public void start() {
if(currentLocation!=null){
new Thread(){
public void run(){
String temp=reverseGeocode(currentLocation);
if(temp!=null&&temp.length()>=2)
city=temp;
}
}.start();
}else{
System.out.println("GetCity.start()未獲得location");
}
}

/**
* 獲得城市
* @return
*/
public String getCity(){
return city;
}

/**
* 通過Google map api 解析出城市
* @param loc
* @return
*/
public String reverseGeocode(Location loc) {
// http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&oe=utf8&sensor=true_or_false&key=your_api_key
String localityName = "";
HttpURLConnection connection = null;
URL serverAddress = null;

try {
// build the URL using the latitude & longitude you want to lookup
// NOTE: I chose XML return format here but you can choose something
// else
serverAddress = new URL("http://maps.google.com/maps/geo?q="
+ Double.toString(loc.getLatitude()) + ","
+ Double.toString(loc.getLongitude())
+ "&output=xml&oe=utf8&sensor=true&key="
+ GOOGLE_MAPS_API_KEY);
// set up out communications stuff
connection = null;

// Set up the initial connection
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);

connection.connect();

try {
InputStreamReader isr = new InputStreamReader(connection
.getInputStream());
InputSource source = new InputSource(isr);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xr = parser.getXMLReader();
GoogleReverseGeocodeXmlHandler handler = new GoogleReverseGeocodeXmlHandler();

xr.setContentHandler(handler);
xr.parse(source);

localityName = handler.getLocalityName();
System.out.println("GetCity.reverseGeocode()"+localityName);
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("GetCity.reverseGeocode()"+ex);
}

return localityName;
}

/**
* The final piece of this puzzle is parsing the xml tha

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.