activity_map.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:background="@color/white"
android:orientation="vertical" >
<include layout="@layout/common_header" />
<com.amap.api.maps2d.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
對應的activity文件配置
package com.sunhoo.yjy.activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sunhoo.yjy.R;
import com.sunhoo.yjy.util.SPUtils;
import java.io.File;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MapActivity extends BaseActivity implements LocationSource, AMapLocationListener,PoiSearch.OnPoiSearchListener,View.OnClickListener {
//AMap是地圖對象
private AMap aMap;
private MapView mapView;
//聲明AMapLocationClient類對象,定位發起端
private AMapLocationClient mLocationClient = null;
//聲明mLocationOption對象,定位參數
public AMapLocationClientOption mLocationOption = null;
//聲明mListener對象,定位監聽器
private OnLocationChangedListener mListener = null;
//標識,用於判斷是否只顯示一次定位信息和用戶從新定位
private boolean isFirstLoc = true;
private Double myLat;
private Double myLongt;
private Double endLat;
private Double endLongt;
private TextView go;
private ArrayList<PoiItem> poiItems;
private Dialog SelectPayMethodDialog;
@Override
public void customTitleCenter(TextView titleCenter) {
titleCenter.setText("找廁所");
}
@Override
protected int getLayoutId() {
return R.layout.activity_map;
}
@Override
protected void initView(Bundle savedInstanceState) {
//獲取地圖控件引用
mapView = (MapView) findViewById(R.id.map);
go = (TextView) findViewById(R.id.go);
//在activity執行onCreate時執行mMapView.onCreate(savedInstanceState),實現地圖生命週期管理
mapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mapView.getMap();
//設置顯示定位按鈕 而且能夠點擊
UiSettings settings = aMap.getUiSettings();
aMap.setLocationSource(this);//設置了定位的監聽
// 是否顯示定位按鈕
settings.setMyLocationButtonEnabled(true);
aMap.setMyLocationEnabled(true);//顯示定位層而且能夠觸發定位,默認是flase
}
aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(final Marker marker) {
marker.getSnippet();
//Toast.makeText(getApplicationContext(),"我要跳轉了"+marker.getSnippet(), Toast.LENGTH_LONG).show();
SelectPayMethodDialog = new Dialog(MapActivity.this, R.style.Dialog);
SelectPayMethodDialog.setCanceledOnTouchOutside(false);
View view = LayoutInflater.from(MapActivity.this).inflate(R.layout.layout_navigation, null);
SelectPayMethodDialog.setContentView(view);
LinearLayout paymethod_selector_alipay = view.findViewById(R.id.paymethod_selector_alipay);
LinearLayout ll_paymethod_close = view.findViewById(R.id.ll_paymethod_close);
TextView distance = view.findViewById(R.id.distance);
final LatLng latlngA = new LatLng(myLat, myLongt);
int range = (int)AMapUtils.calculateLineDistance(latlngA, marker.getPosition());
distance.setText(range + "米");
TextView go=view.findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SelectPayMethodDialog.dismiss();
Double latitude=marker.getPosition().latitude;
Double longitude=marker.getPosition().longitude;
//Toast.makeText(mContext, latLng, Toast.LENGTH_SHORT).show();
//String[] s= latLng.split(",");
placeOrder(latitude,longitude);
}
});
ll_paymethod_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SelectPayMethodDialog.dismiss();
}
});
//initData();
Window window = SelectPayMethodDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
Display dis = getWindowManager().getDefaultDisplay();
int width = dis.getWidth();
lp.width = width;
window.setGravity(Gravity.BOTTOM);
window.setAttributes(lp);
SelectPayMethodDialog.show();
return false;
}
});
//開始定位
location();
//initData();
}
private void initData() {
}
private void placeOrder(Double latitude,Double longitude){
// Toast.makeText(mContext, "latitude"+"----"+"longitude", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent("android.intent.action.VIEW",
// android.net.Uri.parse("androidamap://navi?sourceApplication=amap&lat=" + latitude + "&lon=" + longitude + "&dev=1&style=0&t=2"));
// intent.setPackage("com.autonavi.minimap");
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
// if (isInstallByread("com.autonavi.minimap")) {
// startActivity(intent);
// } else {
// Toast.makeText(mContext, "沒有安裝高德地圖客戶端", Toast.LENGTH_SHORT).show();
// }
Intent intent2 = null;
try {
intent2 = Intent.getIntent("androidamap://route?sourceApplication=softname&sname=個人位置&dlat="+latitude+"&dlon="+longitude+"&dev=0&m=0&t=4");
} catch (URISyntaxException e) {
e.printStackTrace();
}
if(isInstallByread("com.autonavi.minimap")){
startActivity(intent2);
//Log.e(TAG, "高德地圖客戶端已經安裝") ;
}else {
Toast.makeText(mContext, "沒有安裝高德地圖客戶端", Toast.LENGTH_SHORT).show();
}
}
private boolean isInstallByread(String packageName) {
return new File("/data/data/" + packageName).exists();
}
@Override
protected void initEventListeners() {
}
private void location() {
//初始化定位
mLocationClient = new AMapLocationClient(getApplicationContext());
//設置定位回調監聽
mLocationClient.setLocationListener(this);
//初始化定位參數
mLocationOption = new AMapLocationClientOption();
//設置定位模式爲Hight_Accuracy高精度模式,Battery_Saving爲低功耗模式,Device_Sensors是僅設備模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//設置是否返回地址信息(默認返回地址信息)
mLocationOption.setNeedAddress(true);
//設置是否只定位一次,默認爲false
mLocationOption.setOnceLocation(false);
//設置是否強制刷新WIFI,默認爲強制刷新
mLocationOption.setWifiActiveScan(true);
//設置是否容許模擬位置,默認爲false,不容許模擬位置
mLocationOption.setMockEnable(false);
//設置定位間隔,單位毫秒,默認爲2000ms
mLocationOption.setInterval(2000);
//給定位客戶端對象設置定位參數
mLocationClient.setLocationOption(mLocationOption);
//啓動定位
mLocationClient.startLocation();
// @Override
// public boolean onMarkerClick(Marker marker) {
// final MarkerOptions moo = marker.getOptions();
// showMapView(marker.getTitle(), marker.getSnippet(), moo);
// return false;
// }
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理
mapView.onDestroy();
mLocationClient.stopLocation();//中止定位
mLocationClient.onDestroy();//銷燬定位客戶端。
}
@Override
public void onResume() {
super.onResume();
//在activity執行onResume時執行mMapView.onResume (),實現地圖生命週期管理
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity執行onPause時執行mMapView.onPause (),實現地圖生命週期管理
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity執行onSaveInstanceState時執行mMapView.onSaveInstanceState (outState),實現地圖生命週期管理
mapView.onSaveInstanceState(outState);
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
//定位成功回調信息,設置相關消息
aMapLocation.getLocationType();//獲取當前定位結果來源,如網絡定位結果,詳見官方定位類型表
myLat= aMapLocation.getLatitude();//獲取緯度
myLongt= aMapLocation.getLongitude();//獲取經度
aMapLocation.getAccuracy();//獲取精度信息
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(aMapLocation.getTime());
df.format(date);//定位時間
aMapLocation.getAddress();//地址,若是option中設置isNeedAddress爲false,則沒有此結果,網絡定位結果中會有地址信息,GPS定位不返回地址信息。
aMapLocation.getCountry();//國家信息
aMapLocation.getProvince();//省信息
aMapLocation.getCity();//城市信息
aMapLocation.getDistrict();//城區信息
aMapLocation.getStreet();//街道信息
aMapLocation.getStreetNum();//街道門牌號信息
aMapLocation.getCityCode();//城市編碼
aMapLocation.getAdCode();//地區編碼
// 若是不設置標誌位,此時再拖動地圖時,它會不斷將地圖移動到當前的位置
if (isFirstLoc) {
//設置縮放級別
aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
//將地圖移動到定位點
aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
//點擊定位按鈕 可以將地圖的中心移動到定位點
mListener.onLocationChanged(aMapLocation);
//添加圖釘
aMap.addMarker(getMarkerOption("",aMapLocation.getLatitude(),aMapLocation.getLongitude(),R.drawable.position));
//獲取定位信息
//定義Maker座標點,深圳大學經度和緯度113.943062,22.54069
//設置的時候經緯度是反的 緯度在前,經度在後
doSearchQuery(aMapLocation.getLatitude(),aMapLocation.getLongitude());
StringBuffer buffer = new StringBuffer();
buffer.append(aMapLocation.getCountry() + ""
+ aMapLocation.getProvince() + ""
+ aMapLocation.getCity() + ""
+ aMapLocation.getProvince() + ""
+ aMapLocation.getDistrict() + ""
+ aMapLocation.getStreet() + ""
+ aMapLocation.getStreetNum());
Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
isFirstLoc = false;
}
} else {
//顯示錯誤信息ErrCode是錯誤碼,errInfo是錯誤信息,詳見錯誤碼錶。
Log.e("AmapError", "location Error, ErrCode:"
+ aMapLocation.getErrorCode() + ", errInfo:"
+ aMapLocation.getErrorInfo());
Toast.makeText(getApplicationContext(), "定位失敗", Toast.LENGTH_LONG).show();
}
}
}
/**
* 自定義圖標
* @return
*/
public MarkerOptions getMarkerOption(String str, double lat, double lgt, int a){
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.fromResource(a));
markerOptions.position(new LatLng(lat,lgt));
markerOptions.title(str);
endLat=lat;
endLongt=lgt;
markerOptions.snippet("緯度:" + lat + " 經度:" + lgt);
markerOptions.period(100);
return markerOptions;
}
protected void doSearchQuery(Double myLat,Double myLongt) {
String keyWord = "廁所";
Integer currentPage = 0;
PoiSearch.Query query = new PoiSearch.Query(keyWord, "", "");// 第一個參數表示搜索字符串,第二個參數表示poi搜索類型,第三個參數表示poi搜索區域(空字符串表明全國)
query.setPageSize(10);// 設置每頁最多返回多少條poiitem
query.setPageNum(currentPage);// 設置查第一頁
LatLonPoint lp = new LatLonPoint(myLat, myLongt);
if (lp != null) {
PoiSearch poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.setBound(new PoiSearch.SearchBound(lp, 1000, true));
// 設置搜索區域爲以lp點爲圓心,其周圍10000米範圍
poiSearch.searchPOIAsyn();// 異步搜索
}
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mListener = onLocationChangedListener;
}
@Override
public void deactivate() {
mListener = null;
}
@Override
public void onPoiSearched(PoiResult poiResult, int i) {
//經過回調接口 onPoiSearched 解析返回的結果,將查詢到的 POI 以繪製點的方式顯示在地圖上。
if(i == 1000){
if(poiResult != null && poiResult.getPois() != null && poiResult.getPois().size() != 0){
poiItems = poiResult.getPois();
for(int j=0;j<poiItems.size();j++)
{
LatLonPoint latLonPoint = poiItems.get(j).getLatLonPoint();
aMap.addMarker(getMarkerOption("",latLonPoint.getLatitude(),latLonPoint.getLongitude(),R.drawable.wc));
}
}
}
}
@Override
public void onPoiItemSearched(PoiItem poiItem, int i) {
}
@Override
public void onClick(View view) {
}
}
須要的jar包
在build.gradle
dependencies
compile 'com.amap.api:map2d:latest.integration'
compile 'com.amap.api:location:latest.integration'
文章禁止轉載,本問確信有用,且內容真實