百度地图之地址信息和坐标的转换

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

在实际运用中,经常需要进行地理编码和地理反编码,即将地址信息转换成坐标和将坐标转换成地址信息,此demo就是用来展示如何进行地理编码搜索(用地址检索坐标)、反地理编码搜索(用坐标检索地址)以及展示如何使用ItemizedOverlay在地图上标注结果点,代码原型来自百度Demo,代码如下:

Activity:

package com.home;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class GeoCoderActivity extends Activity implements OnClickListener {
	// UI相关
	private Button mBtnReverseGeoCode = null; // 将坐标反编码为地址
	private Button mBtnGeoCode = null; // 将地址编码为坐标
	private EditText lat = null;
	private EditText lon = null;
	private EditText editCity = null;
	private EditText editGeoCodeKey = null;
	// 地图相关
	private MapView mMapView = null; // 地图View
	// 搜索相关
	private MKSearch mSearch = null; // 搜索模块,也可去掉地图模块独立使用

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DemoApplication app = (DemoApplication) this.getApplication();
		setContentView(R.layout.geocoder);
		CharSequence titleLable = "地理编码功能";
		setTitle(titleLable);

		// 地图初始化
		mMapView = (MapView) findViewById(R.id.geocoder_bmapView);
		mMapView.getController().enableClick(true);
		mMapView.getController().setZoom(12);

		// UI初始化
		lat = (EditText) findViewById(R.id.geocoder_et_lat);
		lon = (EditText) findViewById(R.id.geocoder_et_lon);
		editCity = (EditText) findViewById(R.id.geocoder_et_city);
		editGeoCodeKey = (EditText) findViewById(R.id.geocoder_et_geocodekey);
		mBtnReverseGeoCode = (Button) findViewById(R.id.geocoder_btn_reversegeocode);
		mBtnGeoCode = (Button) findViewById(R.id.geocoder_btn_geocode);
		mBtnReverseGeoCode.setOnClickListener(this);
		mBtnGeoCode.setOnClickListener(this);

		// 初始化搜索模块,注册事件监听
		mSearch = new MKSearch();
		mSearch.init(app.mBMapManager, new MKSearchListener() {
			@Override
			public void onGetPoiDetailSearchResult(int type, int error) {
			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
				if (error != 0) {
					String str = String.format("错误号:%d", error);
					Toast.makeText(GeoCoderActivity.this, str,
							Toast.LENGTH_LONG).show();
					return;
				}
				// 地图移动到该点
				mMapView.getController().animateTo(res.geoPt);
				if (res.type == MKAddrInfo.MK_GEOCODE) {
					// 地理编码:通过地址检索坐标点
					String strInfo = String.format("纬度:%f 经度:%f",
							res.geoPt.getLatitudeE6() / 1e6,
							res.geoPt.getLongitudeE6() / 1e6);
					Toast.makeText(GeoCoderActivity.this, strInfo,
							Toast.LENGTH_LONG).show();
				}
				if (res.type == MKAddrInfo.MK_REVERSEGEOCODE) {
					// 反地理编码:通过坐标点检索详细地址及周边poi
					String strInfo = res.strAddr;
					Toast.makeText(GeoCoderActivity.this, strInfo,
							Toast.LENGTH_LONG).show();

				}
				// 生成ItemizedOverlay图层用来标注结果点
				ItemizedOverlay<OverlayItem> itemOverlay = new ItemizedOverlay<OverlayItem>(
						null, mMapView);
				// 生成Item
				OverlayItem item = new OverlayItem(res.geoPt, "", null);
				// 得到需要标在地图上的资源
				Drawable marker = getResources().getDrawable(
						R.drawable.icon_markf);
				// 为maker定义位置和边界
				marker.setBounds(0, 0, marker.getIntrinsicWidth(),
						marker.getIntrinsicHeight());
				// 给item设置marker
				item.setMarker(marker);
				// 在图层上添加item
				itemOverlay.addItem(item);

				// 清除地图其他图层
				mMapView.getOverlays().clear();
				// 添加一个标注ItemizedOverlay图层
				mMapView.getOverlays().add(itemOverlay);
				// 执行刷新使生效
				mMapView.refresh();
			}

			public void onGetPoiResult(MKPoiResult res, int type, int error) {

			}

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
			}

			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
			}

			@Override
			public void onGetShareUrlResult(MKShareUrlResult result, int type,
					int error) {
			}

		});

	}

	@Override
	public void onClick(View v) {
		if (v == mBtnGeoCode) {
			// Geo搜索
			mSearch.geocode(editGeoCodeKey.getText().toString(), editCity
					.getText().toString());
		}
		if (v == mBtnReverseGeoCode) {
			GeoPoint ptCenter = new GeoPoint((int) (Float.valueOf(lat.getText()
					.toString()) * 1e6), (int) (Float.valueOf(lon.getText()
					.toString()) * 1e6));
			// 反Geo搜索
			mSearch.reverseGeocode(ptCenter);
		}
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}
}


布局XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/geocoder_et_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="北京" />

        <EditText
            android:id="@+id/geocoder_et_geocodekey"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="海淀区上地十街10号" />

        <Button
            android:id="@+id/geocoder_btn_geocode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_style"
            android:text="Geo" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/geocoder_et_lat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="39.904965" />

        <EditText
            android:id="@+id/geocoder_et_lon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="116.327764" />

        <Button
            android:id="@+id/geocoder_btn_reversegeocode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_style"
            android:text="ReverseGeo" />
    </LinearLayout>

    <com.baidu.mapapi.map.MapView
        android:id="@+id/geocoder_bmapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />

</LinearLayout>


配置文件同之前地图示例

附上图片效果:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <meta name="keywords" content="百度地图,百度地图API,百度地图自定义工具,百度地图所见即所得工具" /> <meta name="description" content="百度地图API自定义地图,帮助用户在可视化操作下生成百度地图" /> <title>百度地图API自定义地图</title> <!--引用百度地图API--> <style type="text/css"> html,body{margin:0;padding:0;} .iw_poi_title {color:#CC5522;font-size:14px;font-weight:bold;overflow:hidden;padding-right:13px;white-space:nowrap} .iw_poi_content {font:12px arial,sans-serif;overflow:visible;padding-top:4px;white-space:-moz-pre-wrap;word-wrap:break-word} </style> [removed][removed] </head> <body> <!--百度地图容器--> <div solid 1px;margin:auto auto;" id="dituContent"></div> </body> [removed] //创建和初始化地图函数: function initMap(){ createMap();//创建地图 setMapEvent();//设置地图事件 addMapControl();//向地图添加控件 } //创建地图函数: function createMap(){ var map = new BMap.Map("dituContent");//在百度地图容器中创建一个地图 var point = new BMap.Point(116.395645,39.929986);//定义一个中心点坐标 map.centerAndZoom(point,12);//设定地图的中心点和坐标并将地图显示在地图容器中 window.map = map;//将map变量存储在全局 } //地图事件设置函数: function setMapEvent(){ map.enableDragging();//启用地图拖拽事件,默认启用(可不写) map.enableScrollWheelZoom();//启用地图滚轮放大缩小 map.enableDoubleClickZoom();//启用鼠标双击放大,默认启用(可不写) map.enableKeyboard();//启用键盘上下左右键移动地图 } //地图控件添加函数: function addMapControl(){ //向地图中添加缩放控件 var ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT,type:BMAP_NAVIGATION_CONTROL_LARGE}); map.addControl(ctrl_nav); //向地图中添加缩略图控件 var ctrl_ove = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,isOpen:1}); map.addControl(ctrl_ove); //向地图中添加比例尺控件 var ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT}); map.addControl(ctrl_sca); } initMap();//创建和初始化地图 [removed] </html>
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010142437

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值