android baidu_map百度地图

MainActivity.java

package com.example.bdmap;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfigeration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.DistanceUtil;

public class MainActivity extends Activity implements
OnGetGeoCoderResultListener {

public MapView mapView;
public BaiduMap mBaiduMap;
public LocationMode mLocationMode;
public BitmapDescriptor mBitmapDescriptor;
public LocationClient mLocationClient;
public MyLocationListenner myLocationListener = new MyLocationListenner();
boolean isFirst = true;
boolean isFirsts = true;
public Marker marker=null;
public Marker markers=null;
public GeoCoder geoCoder=null;
private InfoWindow mInfoWindow=null;
Map<Marker, ReverseGeoCodeResult> hashMapMarker = new HashMap<Marker, ReverseGeoCodeResult>();
public Button positioning;
public LatLng MarkerLatLng=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SDKInitializer必须在控件加载前初始化
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
initGeoCoder();
initView();
}

// 初始化geoCoder
private void initGeoCoder() {
// TODO Auto-generated method stub
geoCoder = GeoCoder.newInstance();
geoCoder.setOnGetGeoCodeResultListener(this);
}

private void initView() {
// TODO Auto-generated method stub
mapView = (MapView) findViewById(R.id.mapView);
mBaiduMap = mapView.getMap();
// mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);

// 设置定位按钮点击事件
positioning = (Button) findViewById(R.id.positioning);
positioning.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (marker!= null) {
MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory
.newLatLng(MarkerLatLng);
// 设置动画
mBaiduMap.animateMapStatus(mapStatusUpdate);
}
}
});

// 开启定位图层
mBaiduMap.setMyLocationEnabled(true);
mLocationClient = new LocationClient(this);
// 通过继承BDLocationListener获取当前位置
mLocationClient.registerLocationListener(myLocationListener);
LocationClientOption LocationClientOption = new LocationClientOption();
// 打开gps
LocationClientOption.setOpenGps(true);
// 设置坐标类型
LocationClientOption.setCoorType("bd09ll");
// 设置更新时间
LocationClientOption.setScanSpan(2000);
mLocationClient.setLocOption(LocationClientOption);
mLocationClient.start();
// 移动或改变地图状态时清屏
mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {

@Override
public void onMapStatusChangeStart(MapStatus arg0) {
// TODO Auto-generated method stub
mBaiduMap.hideInfoWindow();
}

@Override
public void onMapStatusChangeFinish(MapStatus arg0) {
// TODO Auto-generated method stub
mBaiduMap.hideInfoWindow();
}

@Override
public void onMapStatusChange(MapStatus arg0) {
// TODO Auto-generated method stub
mBaiduMap.hideInfoWindow();
}
});

// 地图图标点击事件
mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker markert) {
// TODO Auto-generated method stubMap<Marker,
// ReverseGeoCodeResult>
Button button = new Button(getApplicationContext());
button.setBackgroundResource(R.drawable.popup);
LatLng latLng = null;
OnInfoWindowClickListener listener = null;
for (Map.Entry<Marker, ReverseGeoCodeResult> m : hashMapMarker
.entrySet()) {
if (markert == m.getKey()) {
button.setText(m.getValue().getAddress());
button.setTextColor(Color.BLACK);
if (marker == m.getKey()) {
latLng = marker.getPosition();
} else {
latLng = markers.getPosition();
}
listener = new OnInfoWindowClickListener() {
public void onInfoWindowClick() {
mBaiduMap.hideInfoWindow();
}
};
}
}
Point point = mBaiduMap.getProjection()
.toScreenLocation(latLng);
point.y -= 50;
LatLng latLngp = mBaiduMap.getProjection().fromScreenLocation(
point);
mInfoWindow = new InfoWindow(button, latLngp, listener);
mBaiduMap.showInfoWindow(mInfoWindow);
return true;
}
});
}

public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(final BDLocation location) {
if (location == null || mapView == null)
return;
// 获取当前经纬度并保持到MyLocationData中
MyLocationData locationData = new MyLocationData.Builder()
.accuracy(location.getRadius()).direction(0)
.latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
// 显示默认图标
// mBaiduMap.setMyLocationData(locationData);

// 更新图标位置
if (marker==null&&isFirst) {
LatLng point = new LatLng(locationData.latitude,
locationData.longitude);
MarkerLatLng=point;
geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
.location(point));
} else {
LatLng point = new LatLng(locationData.latitude,
locationData.longitude);
MarkerLatLng=point;
geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
.location(point));
trun=false;
}
}

public void onReceivePoi(BDLocation poiLocation) {
}
}

// 设置反Geo和距离按钮点击事件
public void buttonListener(View view) {
if (view.getId() == R.id.geoCoderF) {
EditText latitude = (EditText) findViewById(R.id.latitude);
EditText longitude = (EditText) findViewById(R.id.longitude);
if (!latitude.equals("") && !longitude.equals("")) {
try {
if(!isFirst){
trun=true;
LatLng latLng = new LatLng((Float.valueOf(latitude
.getText().toString())), (Float.valueOf(longitude
.getText().toString())));
geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
.location(latLng));
}

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Toast.makeText(MainActivity.this, "输入坐标不正确",
Toast.LENGTH_SHORT).show();
}

}
}
if (view.getId() == R.id.distance) {
if (hashMapMarker.size() > 1) {
LatLng latLng = hashMapMarker.get(marker).getLocation();
LatLng latLngs = hashMapMarker.get(markers).getLocation();
double distances = DistanceUtil.getDistance(latLng, latLngs) / 1000;
DecimalFormat decimalFormat = new DecimalFormat("#.00");
TextView textDistance = (TextView) findViewById(R.id.distanceTextView);
textDistance.setText("~" + decimalFormat.format(distances)
+ "公里");
Toast.makeText(MainActivity.this,
"~" + decimalFormat.format(distances) + "公里",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "选择点", Toast.LENGTH_SHORT)
.show();
}
}
}

// 根据地理位置获取经纬度
@Override
public void onGetGeoCodeResult(GeoCodeResult result) {
// TODO Auto-generated method stub
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MainActivity.this, "未能找到结果", Toast.LENGTH_SHORT)
.show();
}
}

// 根据经纬度获取地理位置
public boolean trun=false;
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
// TODO Auto-generated method stub
if (result.getAddress().equals("") || result == null
|| result.error != SearchResult.ERRORNO.NO_ERROR) {
//尝试打开GPS及网络
if(trun)
{
Toast.makeText(MainActivity.this, "未能找到该位置信息",Toast.LENGTH_SHORT).show();
}

} else {
BitmapDescriptor bitmap;
OverlayOptions option;
if (isFirst) {
isFirst = false;
bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon);
option = new MarkerOptions().position(result.getLocation())
.icon(bitmap);
marker = (Marker) mBaiduMap.addOverlay(option);
hashMapMarker.put(marker, result);

LatLng latLng = new LatLng(result.getLocation().latitude,
result.getLocation().longitude);
MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory
.newLatLng(latLng);
mBaiduMap.animateMapStatus(mapStatusUpdate);
Toast.makeText(MainActivity.this, result.getAddress(),
Toast.LENGTH_SHORT).show();

} else {
if(trun){

if (isFirsts) {
isFirsts = false;
bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.icon_marka);
option = new MarkerOptions().position(result.getLocation())
.icon(bitmap);
markers = (Marker) mBaiduMap.addOverlay(option);
hashMapMarker.put(markers, result);
}else {
LatLng latLng = new LatLng(result.getLocation().latitude,
result.getLocation().longitude);
markers.setPosition(latLng);
hashMapMarker.put(markers, result);
}

LatLng latLng = new LatLng(result.getLocation().latitude,
result.getLocation().longitude);
MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory
.newLatLng(latLng);
mBaiduMap.animateMapStatus(mapStatusUpdate);
Toast.makeText(MainActivity.this, result.getAddress(),
Toast.LENGTH_SHORT).show();

}else
{
MarkerLatLng = new LatLng(result.getLocation().latitude,
result.getLocation().longitude);
marker.setPosition(MarkerLatLng);
hashMapMarker.put(marker, result);
}
}
}
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
mLocationClient.stop();
mBaiduMap.setMyLocationEnabled(false);
mapView.onDestroy();
marker=null;
markers=null;
MarkerLatLng=null;
mapView = null;
super.onDestroy();
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
mapView.onPause();
super.onPause();
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
mapView.onResume();
super.onResume();
}





@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode==KeyEvent.KEYCODE_BACK){
//1
this.finish();
//ActivityManager manager=(ActivityManager) getSystemService(ACTIVITY_SERVICE);
//manager.killBackgroundProcesses("com.example.bdmap");
//manager.restartPackage("com.example.bdmap");

}

return super.onKeyDown(keyCode, event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

activity_main.xml

<LinearLayout 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"
android:orientation="vertical"
>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="5"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/latitude"
/>
<EditText
android:id="@+id/latitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="22.55"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/longitude"
/>
<EditText
android:id="@+id/longitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="113.9"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/geoCoderF"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="buttonListener"
android:text="@string/geoCoderF"
/>
<Button
android:id="@+id/distance"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="buttonListener"
android:text="@string/distance"
/>
<TextView
android:id="@+id/distanceTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dip"
android:layout_weight="1"
android:onClick="buttonListener"
/>
</LinearLayout>
</LinearLayout>

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
>
<com.baidu.mapapi.map.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
/>
<Button
android:id="@+id/positioning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="50dip"
android:background="@drawable/position"/>
</RelativeLayout>

</LinearLayout>

strings.xml

<resources>

<string name="app_name">BDMap</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="geoCoderF">反Geo</string>
<string name="geoCoder">Geo</string>
<string name="latitude">经度</string>
<string name="longitude">纬度</string>
<string name="distance">距离</string>
</resources>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bdmap"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />

<permission android:name="android.permission.BAIDU_LOCATION_SERVICE" >
</permission>

<uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" >
</uses-permission>
<!-- <uses-permission android:name="android.permission.WRITE_APN_SETTINGS"></uses-permission> -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
</uses-permission>
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- SDK1.5需要android.permission.GET_TASKS权限判断本程序是否为当前运行的应用? -->
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.CAMERA" >
</uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!-- 来电消音 -->
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" >
</uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="false"
android:resizeable="true"
android:smallScreens="true" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="juDScwrocHpeSN6bravN3VAV" />

<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

<!-- 百度定位服务 -->
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" >
</service>
</application>
</manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值