利用google map 查询全国城市坐标

来源:互联网 发布:linux c编程一站式 编辑:程序博客网 时间:2024/04/28 23:43

                             用map功能查询全国城市的地理坐标

 

       最近做项目遇到一个问题,需要查询城市的地理坐标。但是手机网络的限制,查询速度不尽人意。于是就想建个本地数据库,但是全国的数据量也不大,建数据库有点大题小做的感觉。那么就把数据写进xml文件里面吧。

        首先建个项目工程。因为用的google map API,肯定用到了API key,至于怎么获取API key ,我就不在这里重复了。网上有很多。简单的建个布局。

 

 

以下是布局的内容:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<view
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:apiKey="0x2VpyfPAxM2FfTkpEJrQ556tjnyOEiLFfqbS_g"    // 这就是API key
        class="com.google.android.maps.MapView"
        android:clickable="true"
        android:enabled="true"
        tools:context=".MainActivity" />

</RelativeLayout>

 

      使用地图需要添加两个权限:

<uses-library android:name="com.google.android.maps"/> 

<uses-permission android:name="android.permission.INTERNET"/>

然后准备一个txt文件。将要全国的城市信息写上,网上有。

 

 
将这个TXT文件拷贝到工程目录下:
 
然后打开文件,读取文件里的信息。依次查询信息,再将查到的信息写到SharedPreferences 里面。这样就OK了。下面是实现代码:
 

   private void readRawdata()
   {
      Resources res = this.getResources();
      InputStream in = null;
      BufferedReader br = null;
      Geocoder  gc = new Geocoder(this,Locale.CHINA);
     
      try
      {
       in = res.openRawResource(R.raw.cityname);
       String city;
       br = new BufferedReader(new InputStreamReader(in,"GBK"));
       while((city = br.readLine()) !=null)
       {
         String cityname = city +"市";   // 在每个城市名后面添加一个“市”
        try{
         List<Address> address = gc.getFromLocationName(cityname, 1);
                  StringBuilder sb = new StringBuilder();
                  if(address.size() > 0)
                  {
                       Address adsLocation = address.get(0);
                       sb.append(adsLocation.getLatitude()).append("#");
                       sb.append(adsLocation.getLongitude());
                      
                       editor.putString(cityname, sb.toString());   // 将查询得到的结果写进SharedPreferences里
                       editor.commit();
                   }
        }catch(Exception e)
     {
       e.printStackTrace();
     }
                
       }
       
      }
      catch(NotFoundException e)
      {
        e.printStackTrace();
      } catch (UnsupportedEncodingException e)
   {
    Toast.makeText(this, "文本编码出现异常", 100).show();
    e.printStackTrace();
   } catch (IOException e)
   {
    Toast.makeText(this, "文件读取错误", 100).show();
    e.printStackTrace();
   } finally
   {
    try
    {
     if (in != null)
     {
      in.close();
     }
     if (br != null)
     {
      br.close();
     }
    } catch (IOException e)
    {
     e.printStackTrace();
    }

   }
  }

 

另开个线程调用这个方法就可以了。最后得到的结果:

 

 

我第一次写东西,写的不好的地方希望大家多体谅下,写的不好的地方希望能提出来,大家一起交流一起进步!