Android-谷歌地图-通过当前经纬度获取城市

该文介绍了一个Android应用中实现逆地理编码的方法,通过Google Maps API将经纬度坐标转换为地理位置信息,如城市名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 {
 
   
    static finalString GOOGLE_MAPS_API_KEY = "abcdefg";

    privateLocationManager locationManager;
    privateLocation currentLocation;
    privateString city="全国";
    publicGetCity(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, intarg1,
//                     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 voidstart() {
      if(currentLocation!=null){
         new Thread(){
            public void run(){
               Stringtemp=reverseGeocode(currentLocation);
               if(temp!=null&&temp.length()>=2)
                  city=temp;
            }
         }.start();
      }else{
         System.out.println("GetCity.start()未获得location");
      }
    }
    
    
    publicString getCity(){
      return city;
    }
    
    
    publicString 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 youcan choose something
         // else
         serverAddress = newURL("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 = newInputStreamReader(connection
                  .getInputStream());
            InputSource source = new InputSource(isr);
            SAXParserFactory factory =SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader xr = parser.getXMLReader();
            GoogleReverseGeocodeXmlHandler handler = newGoogleReverseGeocodeXmlHandler();

            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;
    }

    
    public classGoogleReverseGeocodeXmlHandler extends DefaultHandler {
      private boolean inLocalityName = false;
      private boolean finished = false;
      private StringBuilder builder;
      private String localityName;

      public String getLocalityName() {
         return this.localityName;
      }

      @Override
      public void characters(char[] ch, int start, intlength)
            throws SAXException {
         super.characters(ch, start, length);
         if (this.inLocalityName&& !this.finished) {
            if ((ch[start] != '\n')&& (ch[start] != ' ')) {
               builder.append(ch, start, length);
            }
         }
      }

      @Override
      public void endElement(String uri, StringlocalName, String name)
            throws SAXException {
         super.endElement(uri, localName, name);

         if (!this.finished) {
            if (localName.equalsIgnoreCase("LocalityName")){
               this.localityName = builder.toString();
               this.finished = true;
            }

            if (builder != null) {
               builder.setLength(0);
            }
         }
      }

      @Override
      public void startDocument() throws SAXException{
         super.startDocument();
         builder = new StringBuilder();
      }

      @Override
      public void startElement(String uri, StringlocalName, String name,
            Attributes attributes) throws SAXException{
         super.startElement(uri, localName, name,attributes);

         if (localName.equalsIgnoreCase("LocalityName")){
            this.inLocalityName = true;
         }
      }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值