Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發筆記(一百零三):地圖與定位 SDK 實戰

編輯:關於 Android 程式設計

集成地圖 SDK

國內常用的地圖 SDK 就是百度和高德了,二者的用法大同小異,可按照官網上的開發指南一步步來。下面是我在集成地圖 SDK 時遇到的問題說明:

1、點擊基本地圖功能選項,不能打開地圖,彈出「key 驗證出錯!請在 AndroidManifest.xml 文件中檢查 key 設置的」紅色字提示。查看日誌提示「galaxy lib host missing meta-data, make sure you know the right way to integrate galaxy」。該問題是因為 key 值對應的簽名與 app 打包用的簽名不一致。app 在開發時與發布時有兩個不同的簽名,開發時用的是 ADT 預設簽名,查看預設簽名的 SHA1 值可依次選擇「Window」→「Preferences」→「Android」→「Build SHA1 fingerprint」。app 發布時的簽名是密鑰文件的簽名,查看發布簽名的 SHA1 值可依次選擇「File」→「Export」→「Export Android Application」→「Next」後選擇密鑰文件並輸入密碼與 app 輸出路徑→在「Certificate fingerprints」下查看 SHA1 值。

2、百度地圖 SDK 3.6 及以上版本找不到 overlayutil 包。這是因為新版 SDK 的 jar 包不再包含這部分源碼,需到官方 demo 的 src 目錄下獲取源碼加入到開發者自己的工程中,源碼路徑為:BaiduMap_AndroidMapSDK_v3.7.1_Sample\BaiduMapsApiDemo\src\com\baidu\mapapi。

3、在一個工程中同時包含了百度地圖和高德地圖的 sdk,編譯時報錯「Found duplicate file for APK: assets/lineDashTexture.png」。這是因為百度和高德的 sdk,其 jar 包存在同名文件「assets/lineDashTexture.png」,所以無法通過編譯。即百度 sdk 與高德 sdk 是互斥的,不能同時存在於同個工程中,必須分開來使用。

顯示地圖和定位

對於一個地圖 SDK 來說,首先要顯示地圖,然後定位到當前城市。這方面百度地圖和高德地圖的處理程式碼差不多,下面是兩種地圖 sdk 顯示並定位的程式碼例子:

百度地圖

 // 以下主要是定位用到的代碼 private MapView mMapView; private BaiduMap mMapLayer; private LocationClient mLocClient; private boolean isFirstLoc = true;// 是否首次定位 private void initLocation() { mMapView = (MapView) findViewById(R.id.bmapView); mMapView.setVisibility(View.INVISIBLE); mMapLayer = mMapView.getMap(); mMapLayer.setOnMapClickListener(this); mMapLayer.setMyLocationEnabled(true); mLocClient = new LocationClient(this); mLocClient.registerLocationListener(new MyLocationListenner()); LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); option.setCoorType("bd09ll"); option.setScanSpan(1000); option.setIsNeedAddress(true); mLocClient.setLocOption(option); mLocClient.start(); } public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null || mMapView == null) { Log.d(TAG, "location is null or mMapView is null"); return; } m_latitude = location.getLatitude(); m_longitude = location.getLongitude(); String position = String.format("當前位置:%s|%s|%s|%s|%s|%s|%s", location.getProvince(), location.getCity(), location.getDistrict(), location.getStreet(), location.getStreetNumber(), location.getAddrStr(), location.getTime()); loc_position.setText(position); MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) .direction(100).latitude(m_latitude) .longitude(m_longitude).build(); mMapLayer.setMyLocationData(locData); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(m_latitude, m_longitude); MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(ll, 14); mMapLayer.animateMapStatus(update); mMapView.setVisibility(View.VISIBLE); } } public void onReceivePoi(BDLocation poiLocation) { } }

高德地圖

 // 以下主要是定位用到的代碼 private MapView mMapView; private AMap mMapLayer; private AMapLocationClient mLocClient; private boolean isFirstLoc = true; private void initLocation(Bundle savedInstanceState) { mMapView = (MapView) findViewById(R.id.amapView); mMapView.onCreate(savedInstanceState); mMapView.setVisibility(View.INVISIBLE); if (mMapLayer == null) { mMapLayer = mMapView.getMap(); } mMapLayer.setOnMapClickListener(this); mMapLayer.setMyLocationEnabled(true); mMapLayer.setMyLocationType(AMap.LOCATION_TYPE_LOCATE); mLocClient = new AMapLocationClient(this.getApplicationContext()); mLocClient.setLocationListener(new MyLocationListenner()); AMapLocationClientOption option = new AMapLocationClientOption(); option.setLocationMode(AMapLocationMode.Battery_Saving); option.setNeedAddress(true); mLocClient.setLocationOption(option); mLocClient.startLocation(); } public class MyLocationListenner implements AMapLocationListener { @Override public void onLocationChanged(AMapLocation location) { if (location == null || mMapView == null) { Log.d(TAG, "location is null or mMapView is null"); return; } m_latitude = location.getLatitude(); m_longitude = location.getLongitude(); String position = String.format("當前位置:%s|%s|%s|%s|%s|%s|%s", location.getProvince(), location.getCity(), location.getDistrict(), location.getStreet(), location.getAdCode(), location.getAddress(), location.getTime()); loc_position.setText(position); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(m_latitude, m_longitude); CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 12); mMapLayer.moveCamera(update); mMapView.setVisibility(View.VISIBLE); } } }

POI 搜索

POI 即地圖注點,它是「Point of Interest」的縮寫,在地圖上標注地點名稱、類別、經度、緯度等信息,是一個帶位置信息的地圖標注。POI 搜索是地圖 sdk 的一個重要應用,根據關鍵字搜索並在地圖上顯示 POI 結果,這是智能出行的基礎。

下面是使用百度地圖搜索 POI 的截圖:

下面是兩種地圖 sdk 進行 POI 搜索的程式碼例子:

百度地圖

 // 以下主要是POI搜索用到的代碼 private PoiSearch mPoiSearch = null; private SuggestionSearch mSuggestionSearch = null; private AutoCompleteTextView mKey = null; private EditText mScope = null; private Button btn_search, btn_nextpage, btn_cleardata; private ArrayAdapter sugAdapter = null; private int load_Index = 0; private void initMap() { mPoiSearch = PoiSearch.newInstance(); mPoiSearch.setOnGetPoiSearchResultListener(this); mSuggestionSearch = SuggestionSearch.newInstance(); mSuggestionSearch.setOnGetSuggestionResultListener(this); mScope = (EditText) findViewById(R.id.poi_city); mKey = (AutoCompleteTextView) findViewById(R.id.poi_searchkey); btn_search = (Button) findViewById(R.id.search); btn_nextpage = (Button) findViewById(R.id.map_next_data); btn_cleardata = (Button) findViewById(R.id.map_clear_data); btn_search.setOnClickListener(this); btn_nextpage.setOnClickListener(this); btn_cleardata.setOnClickListener(this); sugAdapter = new ArrayAdapter(this, R.layout.spinner_dropdown_item); mKey.setAdapter(sugAdapter); mKey.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { if (cs.length() <= 0) { return; } String city = mScope.getText().toString(); mSuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(cs.toString()).city(city)); } }); } @Override public void onGetSuggestionResult(SuggestionResult res) { if (res == null || res.getAllSuggestions() == null) { return; } else { sugAdapter.clear(); for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) { if (info.key != null) { sugAdapter.add(info.key); } } sugAdapter.notifyDataSetChanged(); } } public void searchButtonProcess(View v) { String keyword = mKey.getText().toString(); if (search_method == SEARCH_CITY) { String city = mScope.getText().toString(); mPoiSearch.searchInCity((new PoiCitySearchOption()).city(city).keyword(keyword).pageNum(load_Index)); } else if (search_method == SEARCH_NEARBY) { LatLng position = new LatLng(m_latitude, m_longitude); int radius = Integer.parseInt(mScope.getText().toString()); mPoiSearch.searchNearby((new PoiNearbySearchOption()).location(position).keyword(keyword).radius(radius).pageNum(load_Index)); } } public void onGetPoiResult(PoiResult result) { if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) { Toast.makeText(this, "未找到結果", Toast.LENGTH_LONG).show(); return; } else if (result.error == SearchResult.ERRORNO.NO_ERROR) { mMapLayer.clear(); PoiOverlay overlay = new MyPoiOverlay(mMapLayer); mMapLayer.setOnMarkerClickListener(overlay); overlay.setData(result); overlay.addToMap(); overlay.zoomToSpan(); } } private class MyPoiOverlay extends PoiOverlay { public MyPoiOverlay(BaiduMap baiduMap) { super(baiduMap); } @Override public boolean onPoiClick(int index) { super.onPoiClick(index); PoiInfo poi = getPoiResult().getAllPoi().get(index); mPoiSearch.searchPoiDetail((new PoiDetailSearchOption()).poiUid(poi.uid)); return true; } }

高德地圖

 // 以下主要是POI搜索用到的代碼 private PoiSearch mPoiSearch = null; private AutoCompleteTextView mKey = null; private EditText mScope = null; private Button btn_search, btn_nextpage, btn_cleardata; private ArrayAdapter sugAdapter = null; private int load_Index = 0; private void initMap() { mScope = (EditText) findViewById(R.id.poi_city); mKey = (AutoCompleteTextView) findViewById(R.id.poi_searchkey); btn_search = (Button) findViewById(R.id.search); btn_nextpage = (Button) findViewById(R.id.map_next_data); btn_cleardata = (Button) findViewById(R.id.map_clear_data); btn_search.setOnClickListener(this); btn_nextpage.setOnClickListener(this); btn_cleardata.setOnClickListener(this); sugAdapter = new ArrayAdapter(this, R.layout.spinner_dropdown_item); mKey.setAdapter(sugAdapter); mKey.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { if (cs.length() <= 0) { return; } String city = mScope.getText().toString(); InputtipsQuery inputquery = new InputtipsQuery(cs.toString(), city); Inputtips inputTips = new Inputtips(GaodeActivity.this, inputquery); inputTips.setInputtipsListener(GaodeActivity.this); inputTips.requestInputtipsAsyn(); } }); } @Override public void onGetInputtips(List tipList, int rCode) { if (rCode != 1000) { Toast.makeText(this, "推薦文字錯誤代碼是"+rCode, Toast.LENGTH_LONG).show(); } else { sugAdapter.clear(); for (Tip info : tipList) { if (info.getName() != null) { sugAdapter.add(info.getName()); } } sugAdapter.notifyDataSetChanged(); } } public void searchButtonProcess(View v) { String keyword = mKey.getText().toString(); if (search_method == SEARCH_CITY) { String city = mScope.getText().toString(); PoiSearch.Query query = new PoiSearch.Query(keyword, null, city); query.setPageSize(10); query.setPageNum(load_Index); mPoiSearch = new PoiSearch(this, query); mPoiSearch.setOnPoiSearchListener(this); mPoiSearch.searchPOIAsyn(); } else if (search_method == SEARCH_NEARBY) { LatLonPoint position = new LatLonPoint(m_latitude, m_longitude); int radius = Integer.parseInt(mScope.getText().toString()); PoiSearch.Query query = new PoiSearch.Query(keyword, null, "福州"); query.setPageSize(10); query.setPageNum(load_Index); mPoiSearch = new PoiSearch(this, query); SearchBound bound = new SearchBound(position, radius); mPoiSearch.setBound(bound); mPoiSearch.setOnPoiSearchListener(this); mPoiSearch.searchPOIAsyn(); } } @Override public void onPoiSearched(PoiResult result, int rCode) { if (rCode != 1000) { Toast.makeText(this, "POI錯誤代碼是"+rCode, Toast.LENGTH_LONG).show(); } else if (result == null || result.getQuery() == null) { Toast.makeText(this, "未找到結果", Toast.LENGTH_LONG).show(); return; } else { mMapLayer.clear(); List poiList = result.getPois(); List suggestionCities = result.getSearchSuggestionCitys(); if (poiList!=null && poiList.size()>0) { PoiOverlay poiOverlay = new PoiOverlay(mMapLayer, poiList); poiOverlay.removeFromMap(); poiOverlay.addToMap(); poiOverlay.zoomToSpan(); mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { marker.showInfoWindow(); return true; } }); } } }

測距、測面積

測量距離和測量面積是地圖 sdk 的又一個應用,除了在地圖上添加標注之外,就是要用到數學的兩個公式。

其中測距用的是勾股定理:一個直角三角形,兩直角邊的平方和等於斜邊的平方。如果兩直角邊為 a 和 b,斜邊為 c,那麼 a*a+b*b=c*c。

測面積用的是海倫公式:利用三角形的三個邊長直接求三角形面積,表達式為 S=√p(p-a)(p-b)(p-c)。基於海倫公式,可以推導出根據多邊形各邊長求多邊形面積的公式,即 S = 0.5 * ( (x0*y1-x1*y0) + (x1*y2-x2*y1) + ... + (xn*y0-x0*yn) )。

兩種地圖 sdk 在測量上的數學原理是一樣的,只在添加地圖標注上有些小差異,下面是使用高德地圖進行測量的截圖:

下面是兩種地圖 sdk 進行測量的程式碼例子:

百度地圖

 // 下面是在地圖上添加繪圖操作 private static int lineColor = 0x55FF0000; private static int arcColor = 0xbb00FFFF; private static int textColor = 0x990000FF; private static int polygonColor = 0x77FFFF00; private static int radius = 100; private ArrayList posArray = new ArrayList(); boolean is_polygon = false; private void addDot(LatLng pos) { if (is_polygon == true && posArray.size() > 1 && MapUtil.isInsidePolygon(pos, posArray) == true) { LatLng centerPos = MapUtil.getCenterPos(posArray); OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff).fontSize(26).fontColor(textColor).text("標題").position(centerPos); mMapLayer.addOverlay(ooText); return; } if (is_polygon == true) { posArray.clear(); is_polygon = false; } boolean is_first = false; LatLng thisPos = pos; if (posArray.size() > 0) { LatLng firstPos = posArray.get(0); int distance = (int) Math.round(MapUtil.getShortDistance(thisPos.longitude, thisPos.latitude, firstPos.longitude, firstPos.latitude)); if (posArray.size()==1 && distance<=0) { return; } else if (posArray.size() > 1) { LatLng lastPos = posArray.get(posArray.size()-1); int lastDistance = (int) Math.round(MapUtil.getShortDistance(thisPos.longitude, thisPos.latitude, lastPos.longitude, lastPos.latitude)); if (lastDistance <= 0) { return; } } if (distance < radius * 2) { thisPos = firstPos; is_first = true; } LatLng lastPos = posArray.get(posArray.size() - 1); List points = new ArrayList(); points.add(lastPos); points.add(thisPos); OverlayOptions ooPolyline = new PolylineOptions().width(2).color(lineColor).points(points); mMapLayer.addOverlay(ooPolyline); distance = (int) Math.round(MapUtil.getShortDistance(thisPos.longitude, thisPos.latitude, lastPos.longitude, lastPos.latitude)); } if (is_first != true) { OverlayOptions ooCircle = new CircleOptions().fillColor(lineColor).center(thisPos).stroke(new Stroke(2, 0xAAFF0000)).radius(radius); mMapLayer.addOverlay(ooCircle); BitmapDescriptor bitmapDesc = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo); OverlayOptions ooMarker = new MarkerOptions().draggable(false).visible(true).icon(bitmapDesc).position(thisPos); mMapLayer.addOverlay(ooMarker); mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { addDot(marker.getPosition()); return true; } }); } else { if (posArray.size() < 3) { posArray.clear(); is_polygon = false; return; } OverlayOptions ooPolygon = new PolygonOptions().points(posArray).stroke(new Stroke(1, 0xFF00FF00)).fillColor(polygonColor); mMapLayer.addOverlay(ooPolygon); is_polygon = true; LatLng centerPos = MapUtil.getCenterPos(posArray); double area = Math.round(MapUtil.getArea(posArray)); } posArray.add(thisPos); if (posArray.size() >= 3) { OverlayOptions ooArc = new ArcOptions().color(arcColor).width(2).points(posArray.get(posArray.size() - 1), posArray.get(posArray.size() - 2), posArray.get(posArray.size() - 3)); mMapLayer.addOverlay(ooArc); } } @Override public void onMapClick(LatLng arg0) { addDot(arg0); }

高德地圖

 // 下面是在地圖上添加繪圖操作 private static int lineColor = 0x55FF0000; private static int arcColor = 0xbb00FFFF; private static int textColor = 0x990000FF; private static int polygonColor = 0x77FFFF00; private static int radius = 100; private ArrayList posArray = new ArrayList(); boolean is_polygon = false; private void addDot(LatLng pos) { if (is_polygon == true && posArray.size() > 1 && MapUtil.isInsidePolygon(pos, posArray) == true) { LatLng centerPos = MapUtil.getCenterPos(posArray); TextOptions ooText = new TextOptions().backgroundColor(0x00ffffff).fontSize(26).fontColor(textColor).text("標題").position(centerPos); mMapLayer.addText(ooText); return; } if (is_polygon == true) { posArray.clear(); is_polygon = false; } boolean is_first = false; LatLng thisPos = pos; if (posArray.size() > 0) { LatLng firstPos = posArray.get(0); int distance = (int) Math.round(MapUtil.getShortDistance(thisPos.longitude, thisPos.latitude, firstPos.longitude, firstPos.latitude)); if (posArray.size()==1 && distance<=0) { return; } else if (posArray.size() > 1) { LatLng lastPos = posArray.get(posArray.size()-1); int lastDistance = (int) Math.round(MapUtil.getShortDistance(thisPos.longitude, thisPos.latitude, lastPos.longitude, lastPos.latitude)); if (lastDistance <= 0) { return; } } if (distance < radius * 2) { thisPos = firstPos; is_first = true; } LatLng lastPos = posArray.get(posArray.size() - 1); List points = new ArrayList(); points.add(lastPos); points.add(thisPos); PolylineOptions ooPolyline = new PolylineOptions().width(2).color(lineColor).addAll(points); mMapLayer.addPolyline(ooPolyline); distance = (int) Math.round(MapUtil.getShortDistance(thisPos.longitude, thisPos.latitude, lastPos.longitude, lastPos.latitude)); } if (is_first != true) { CircleOptions ooCircle = new CircleOptions().fillColor(lineColor).center(thisPos).strokeWidth(2).strokeColor(0xAAFF0000).radius(radius); mMapLayer.addCircle(ooCircle); BitmapDescriptor bitmapDesc = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo); MarkerOptions ooMarker = new MarkerOptions().draggable(false).visible(true).icon(bitmapDesc).position(thisPos); mMapLayer.addMarker(ooMarker); mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { addDot(marker.getPosition()); marker.showInfoWindow(); return true; } }); } else { if (posArray.size() < 3) { posArray.clear(); is_polygon = false; return; } PolygonOptions ooPolygon = new PolygonOptions().addAll(posArray).strokeColor(0xFF00FF00).strokeWidth(1).fillColor(polygonColor); mMapLayer.addPolygon(ooPolygon); is_polygon = true; LatLng centerPos = MapUtil.getCenterPos(posArray); double area = Math.round(MapUtil.getArea(posArray)); } posArray.add(thisPos); if (posArray.size() >= 3) { ArcOptions ooArc = new ArcOptions().strokeColor(arcColor).strokeWidth(2).point(posArray.get(posArray.size() - 1), posArray.get(posArray.size() - 2), posArray.get(posArray.size() - 3)); mMapLayer.addArc(ooArc); } } @Override public void onMapClick(LatLng arg0) { addDot(arg0); }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved