根据地名查找具体地点



 

每一台电脑都要申请属于自己的android:apiKey,要是使用别人的android:apiKey,

则地图只显示方格,不会有实际的地图出现,并且在Android虚拟机重建或者重装电脑的操作系统的时候

也要重新申请android:apiKey,关于如何申请,我在“申请Google Map服务”中已说得很详细。

 

新建一个地图项目。

 

 

准备两个图片,名字分别为:pic_m、arrow

 

 

 

 

在main.xml中:

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:orientation="vertical"

  android:layout_width="fill_parent"

  android:layout_height="fill_parent">

  <TableLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="wrap_content">

     <TableRow>

       <EditText

         android:id="@+id/msg"

         android:layout_width="200px"

         android:layout_height="wrap_content"/>

       <Button

         android:id="@+id/search"

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:text="检索周边信息" />

     </TableRow>

  </TableLayout>

  <com.google.android.maps.MapView

     android:id="@+id/mapview"

     android:clickable="true" android:enabled="true"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:apiKey="0Pm9QrsSh_mwtc6rMyqZMRu71qFpIB51UXVWHmg" />

</LinearLayout>

 

 

 

 

 

在MyOverlayImpl.java中:

 

package com.li.geocode;

 

import java.util.ArrayList;

import java.util.List;

 

import android.app.AlertDialog;

import android.app.Dialog;

import android.content.Context;

import android.content.DialogInterface;

import android.graphics.drawable.Drawable;

 

import com.google.android.maps.ItemizedOverlay;

import com.google.android.maps.OverlayItem;

 

public class MyOverlayImpl extends ItemizedOverlay<OverlayItem> {

  private List<OverlayItem> allOverlayItems = new ArrayList<OverlayItem>();

  private Context context = null;

 

  public MyOverlayImpl(Drawable defaultMarker, Context context) {

     super(boundCenter(defaultMarker));

     this.context = context;

  }

 

  protected OverlayItem createItem(int i) {

     return this.allOverlayItems.get(i);

  }

 

  public int size() {

     return this.allOverlayItems.size();

  }

 

  protected boolean onTap(int index) { // 单击标记图片之后的操作

     OverlayItem item = this.allOverlayItems.get(index); // 取得指定的点

     Dialog dialog = new AlertDialog.Builder(this.context)

         .setIcon(R.drawable.pic_m).setTitle(item.getTitle())

         .setMessage(item.getSnippet())

         .setPositiveButton("关闭", new DialogInterface.OnClickListener() {

 

           public void onClick(DialogInterface dialog, int which) {

 

            }

         }).create();

     dialog.show();

     return true;

  }

 

  public void addOverlayItem(OverlayItem item) {

     this.allOverlayItems.add(item);

     super.populate();

  }

}

 

 

 

 

在MyGeocodeDemo.java中:

 

package com.li.geocode;

 

import java.io.InputStream;

import java.net.URL;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

 

import org.json.JSONArray;

import org.json.JSONObject;

 

import com.google.android.maps.GeoPoint;

import com.google.android.maps.MapActivity;

import com.google.android.maps.MapView;

import com.google.android.maps.OverlayItem;

 

import android.graphics.drawable.Drawable;

import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

 

 

public class MyGeocodeDemo extends MapActivity {

  private EditText msg = null;

  private Button search = null;

  private MapView mapView = null;

 

  @Override

  public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     super.setContentView(R.layout.main);

     this.search = (Button) super.findViewById(R.id.search);

     this.msg = (EditText) super.findViewById(R.id.msg);

     this.mapView = (MapView) super.findViewById(R.id.mapview);

     this.search.setOnClickListener(new SearchOnClickListenerImpl());

  }

 

  private class SearchOnClickListenerImpl implements OnClickListener {

 

     public void onClick(View v) {

       String msg = MyGeocodeDemo.this.msg.getText().toString() ;

       new SearchAsyncTask(msg).execute(0);

     }

 

  }

 

  // 此时要根据异步处理的工具类来向Google上进行数据的提交操作,而后通过返回的JSON数据解析出具体的数据内容

  private class SearchAsyncTask extends AsyncTask<Integer, String, Integer> {

     private String location;

 

     public SearchAsyncTask(String location) {

       this.location = location;

     }

 

     @Override

     protected void onProgressUpdate(String... values) {

       GeoPoint point = new GeoPoint(

            (int) (Double.parseDouble(values[0]) * 1E6),

            (int) (Double.parseDouble(values[1]) * 1E6));

       OverlayItem overlayItem = new OverlayItem(point, "您的位置!", values[2]);

       Drawable drawable = MyGeocodeDemo.this.getResources().getDrawable(

            R.drawable.arrow);

       MyOverlayImpl mol = new MyOverlayImpl(drawable, MyGeocodeDemo.this);

       mol.addOverlayItem(overlayItem) ;

       MyGeocodeDemo.this.mapView.getOverlays().add(mol) ;

       MyGeocodeDemo.this.mapView.setBuiltInZoomControls(true) ;

       MyGeocodeDemo.this.mapView.getController().animateTo(point) ;

     }

 

     @Override

     protected Integer doInBackground(Integer... arg0) {

       Map<String, String> map = null;

       try {

         map = this.parseJson(this.location);

       } catch (Exception e) {

         e.printStackTrace();

       }

       if ("OK".equals(map.get("status"))) { // 操作正常

         this.publishProgress(map.get("latitude"), map.get("longitude"),

              map.get("address")); // 将address数据返回

       } else {

         this.publishProgress("没有查询结果!");

       }

       return null;

     }

 

     private Map<String, String> parseJson(String location) throws Exception {

       Map<String, String> allMap = new HashMap<String, String>();

       StringBuffer buf = new StringBuffer();

       InputStream input = null;

       try {

         URL url = new URL(

              "http://maps.google.com/maps/api/geocode/json?address="

                   + URLEncoder.encode(location, "UTF-8")

                   + "&sensor=false");

         input = url.openStream();

         Scanner scan = new Scanner(input);

         while (scan.hasNext()) {

            buf.append(scan.next()); // 所有的数据都保存在字符串里面

         }

       } catch (Exception e) {

         e.printStackTrace();

         throw e;

       } finally {

         input.close();

       }

       JSONObject allData = new JSONObject(buf.toString());

       allMap.put("status", allData.getString("status"));

       JSONArray jsonArr = allData.getJSONArray("results");

       JSONObject jsonObj = jsonArr.getJSONObject(0);

       allMap.put("address", jsonObj.getString("formatted_address"));

       JSONObject locationJsonObj = jsonObj.getJSONObject("geometry")

            .getJSONObject("location");

       allMap.put("latitude", locationJsonObj.getString("lat")) ;

       allMap.put("longitude", locationJsonObj.getString("lng")) ;

       return allMap;

     }

  }

 

  @Override

  protected boolean isRouteDisplayed() {

     // TODO Auto-generated method stub

     return false;

  }

}

 

 

 

 

在AndroidManifest.xml中修改权限:

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.li.geocode"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="15" />

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

    <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".MyGeocodeDemo"

            android:label="@string/title_activity_my_geocode_demo" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

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

    </application>

 

</manifest>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值