地图与定位SDK

来源:互联网 发布:手机淘宝怎么进入众筹 编辑:程序博客网 时间:2024/06/06 01:33

集成地图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、百度地图SDK3.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显示并定位的代码例子:

百度地图

  1. // 以下主要是定位用到的代码  
  2. private MapView mMapView;  
  3. private BaiduMap mMapLayer;  
  4. private LocationClient mLocClient;  
  5. private boolean isFirstLoc = true;// 是否首次定位  
  6.   
  7. private void initLocation() {  
  8.     mMapView = (MapView) findViewById(R.id.bmapView);  
  9.     // 先隐藏地图,待定位到当前城市时再显示  
  10.     mMapView.setVisibility(View.INVISIBLE);  
  11.     mMapLayer = mMapView.getMap();  
  12.     mMapLayer.setOnMapClickListener(this);  
  13.     // 开启定位图层  
  14.     mMapLayer.setMyLocationEnabled(true);  
  15.     mLocClient = new LocationClient(this);  
  16.     // 设置定位监听器  
  17.     mLocClient.registerLocationListener(new MyLocationListenner());  
  18.     LocationClientOption option = new LocationClientOption();  
  19.     option.setOpenGps(true);// 打开gps  
  20.     option.setCoorType("bd09ll"); // 设置坐标类型  
  21.     option.setScanSpan(1000);  
  22.     option.setIsNeedAddress(true); // 设置true才能获得详细的地址信息  
  23.     // 设置定位参数  
  24.     mLocClient.setLocOption(option);  
  25.     // 开始定位  
  26.     mLocClient.start();  
  27.      //获取最近一次的位置  
  28.     // mLocClient.getLastKnownLocation();  
  29. }  
  30.   
  31. public class MyLocationListenner implements BDLocationListener {  
  32.   
  33.     @Override  
  34.     public void onReceiveLocation(BDLocation location) {  
  35.         // map view 销毁后不在处理新接收的位置  
  36.         if (location == null || mMapView == null) {  
  37.             Log.d(TAG, "location is null or mMapView is null");  
  38.             return;  
  39.         }  
  40.         m_latitude = location.getLatitude();  
  41.         m_longitude = location.getLongitude();  
  42.         String position = String.format("当前位置:%s|%s|%s|%s|%s|%s|%s",  
  43.                 location.getProvince(), location.getCity(),  
  44.                 location.getDistrict(), location.getStreet(),  
  45.                 location.getStreetNumber(), location.getAddrStr(),  
  46.                 location.getTime());  
  47.         loc_position.setText(position);  
  48.         MyLocationData locData = new MyLocationData.Builder()  
  49.                 .accuracy(location.getRadius())  
  50.                 // 此处设置开发者获取到的方向信息,顺时针0-360  
  51.                 .direction(100).latitude(m_latitude)  
  52.                 .longitude(m_longitude).build();  
  53.         mMapLayer.setMyLocationData(locData);  
  54.         if (isFirstLoc) {  
  55.             isFirstLoc = false;  
  56.             LatLng ll = new LatLng(m_latitude, m_longitude);  
  57.             MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(ll, 14);  
  58.             mMapLayer.animateMapStatus(update);  
  59.             // 定位到当前城市时再显示图层  
  60.             mMapView.setVisibility(View.VISIBLE);  
  61.         }  
  62.     }  
  63.   
  64.     public void onReceivePoi(BDLocation poiLocation) {  
  65.     }  

高德地图

  1. // 以下主要是定位用到的代码  
  2. private MapView mMapView;  
  3. private AMap mMapLayer;  
  4. private AMapLocationClient mLocClient;  
  5. private boolean isFirstLoc = true;// 是否首次定位  
  6.   
  7. private void initLocation(Bundle savedInstanceState) {  
  8.     mMapView = (MapView) findViewById(R.id.amapView);  
  9.     mMapView.onCreate(savedInstanceState);  
  10.     // 先隐藏地图,待定位到当前城市时再显示  
  11.     mMapView.setVisibility(View.INVISIBLE);  
  12.     if (mMapLayer == null) {  
  13.         mMapLayer = mMapView.getMap();  
  14.     }  
  15.     mMapLayer.setOnMapClickListener(this);  
  16.     // 开启定位图层  
  17.     mMapLayer.setMyLocationEnabled(true);  
  18.     mMapLayer.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);  
  19.     mLocClient = new AMapLocationClient(this.getApplicationContext());  
  20.     // 设置定位监听器  
  21.     mLocClient.setLocationListener(new MyLocationListenner());  
  22.     AMapLocationClientOption option = new AMapLocationClientOption();  
  23.     option.setLocationMode(AMapLocationMode.Battery_Saving);  
  24.     option.setNeedAddress(true); // 设置true才能获得详细的地址信息  
  25.     // 设置定位参数  
  26.     mLocClient.setLocationOption(option);  
  27.     // 开始定位  
  28.     mLocClient.startLocation();  
  29.      //获取最近一次的位置  
  30.     // mLocClient.getLastKnownLocation();  
  31. }  
  32.   
  33. public class MyLocationListenner implements AMapLocationListener {  
  34.   
  35.     @Override  
  36.     public void onLocationChanged(AMapLocation location) {  
  37.         // map view 销毁后不在处理新接收的位置  
  38.         if (location == null || mMapView == null) {  
  39.             Log.d(TAG, "location is null or mMapView is null");  
  40.             return;  
  41.         }  
  42.         m_latitude = location.getLatitude();  
  43.         m_longitude = location.getLongitude();  
  44.         String position = String.format("当前位置:%s|%s|%s|%s|%s|%s|%s",  
  45.                 location.getProvince(), location.getCity(),  
  46.                 location.getDistrict(), location.getStreet(),  
  47.                 location.getAdCode(), location.getAddress(),  
  48.                 location.getTime());  
  49.         loc_position.setText(position);  
  50.         if (isFirstLoc) {  
  51.             isFirstLoc = false;  
  52.             LatLng ll = new LatLng(m_latitude, m_longitude);  
  53.                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 12);  
  54.             mMapLayer.moveCamera(update);  
  55.             // 定位到当前城市时再显示图层  
  56.             mMapView.setVisibility(View.VISIBLE);  
  57.         }  
  58.     }  

POI搜索

POI即地图注点,它是“Point of Interest”的缩写,在地图上标注地点名称、类别、经度、纬度等信息,是一个带位置信息的地图标注。POI搜索是地图sdk的一个重要应用,根据关键字搜索并在地图上显示POI结果,这是智能出行的基础。
下面是使用百度地图搜索POI的截图:


下面是两种地图sdk进行POI搜索的代码例子:
百度地图

  1. // 以下主要是POI搜索用到的代码  
  2.     private PoiSearch mPoiSearch = null;  
  3.     private SuggestionSearch mSuggestionSearch = null;  
  4.     private AutoCompleteTextView mKey = null;  
  5.     private EditText mScope = null;  
  6.     private Button btn_search, btn_nextpage, btn_cleardata;  
  7.     private ArrayAdapter<String> sugAdapter = null;  
  8.     private int load_Index = 0;  
  9.   
  10.     private void initMap() {  
  11.         mPoiSearch = PoiSearch.newInstance();  
  12.         mPoiSearch.setOnGetPoiSearchResultListener(this);  
  13.         mSuggestionSearch = SuggestionSearch.newInstance();  
  14.         mSuggestionSearch.setOnGetSuggestionResultListener(this);  
  15.         mScope = (EditText) findViewById(R.id.poi_city);  
  16.         mKey = (AutoCompleteTextView) findViewById(R.id.poi_searchkey);  
  17.         btn_search = (Button) findViewById(R.id.search);  
  18.         btn_nextpage = (Button) findViewById(R.id.map_next_data);  
  19.         btn_cleardata = (Button) findViewById(R.id.map_clear_data);  
  20.         btn_search.setOnClickListener(this);  
  21.         btn_nextpage.setOnClickListener(this);  
  22.         btn_cleardata.setOnClickListener(this);  
  23.         sugAdapter = new ArrayAdapter<String>(this, R.layout.spinner_dropdown_item);  
  24.         mKey.setAdapter(sugAdapter);  
  25.   
  26.         // 当输入关键字变化时,动态更新建议列表  
  27.         mKey.addTextChangedListener(new TextWatcher() {  
  28.   
  29.             @Override  
  30.             public void afterTextChanged(Editable arg0) {  
  31.             }  
  32.   
  33.             @Override  
  34.             public void beforeTextChanged(CharSequence arg0, int arg1,  
  35.                     int arg2, int arg3) {  
  36.             }  
  37.   
  38.             @Override  
  39.             public void onTextChanged(CharSequence cs, int arg1, int arg2,  
  40.                     int arg3) {  
  41.                 if (cs.length() <= 0) {  
  42.                     return;  
  43.                 }  
  44.                 String city = mScope.getText().toString();  
  45.                 // 使用建议搜索服务获取建议列表,结果在onGetSuggestionResult中更新  
  46.                 mSuggestionSearch  
  47.                         .requestSuggestion((new SuggestionSearchOption())  
  48.                                 .keyword(cs.toString()).city(city));  
  49.             }  
  50.         });  
  51.     }  
  52.   
  53.     @Override  
  54.     public void onGetSuggestionResult(SuggestionResult res) {  
  55.         if (res == null || res.getAllSuggestions() == null) {  
  56.             return;  
  57.         } else {  
  58.             sugAdapter.clear();  
  59.             for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {  
  60.                 if (info.key != null) {  
  61.                     sugAdapter.add(info.key);  
  62.                 }  
  63.             }  
  64.             sugAdapter.notifyDataSetChanged();  
  65.         }  
  66.     }  
  67.   
  68.     // 影响搜索按钮点击事件  
  69.     public void searchButtonProcess(View v) {  
  70.         Log.d(TAG, "editCity=" + mScope.getText().toString()  
  71.                 + ", editSearchKey=" + mKey.getText().toString()  
  72.                 + ", load_Index=" + load_Index);  
  73.         String keyword = mKey.getText().toString();  
  74.         if (search_method == SEARCH_CITY) {  
  75.             String city = mScope.getText().toString();  
  76.             mPoiSearch.searchInCity((new PoiCitySearchOption()).city(city)  
  77.                     .keyword(keyword).pageNum(load_Index));  
  78.         } else if (search_method == SEARCH_NEARBY) {  
  79.             LatLng position = new LatLng(m_latitude, m_longitude);  
  80.             int radius = Integer.parseInt(mScope.getText().toString());  
  81.             mPoiSearch.searchNearby((new PoiNearbySearchOption())  
  82.                     .location(position).keyword(keyword).radius(radius)  
  83.                     .pageNum(load_Index));  
  84.         }  
  85.     }  
  86.   
  87.     public void goToNextPage(View v) {  
  88.         load_Index++;  
  89.         searchButtonProcess(null);  
  90.     }  
  91.   
  92.     public void onGetPoiResult(PoiResult result) {  
  93.         if (result == null  
  94.                 || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {  
  95.             Toast.makeText(this"未找到结果", Toast.LENGTH_LONG).show();  
  96.             return;  
  97.         } else if (result.error == SearchResult.ERRORNO.NO_ERROR) {  
  98.             mMapLayer.clear();  
  99.             PoiOverlay overlay = new MyPoiOverlay(mMapLayer);  
  100.             mMapLayer.setOnMarkerClickListener(overlay);  
  101.             List<PoiInfo> poiList = result.getAllPoi();  
  102.             overlay.setData(result);  
  103.             overlay.addToMap();  
  104.             overlay.zoomToSpan();  
  105. //          for (PoiInfo poi : poiList) {  
  106. //          String detail = String.format(  
  107. //                  "uid=%s,city=%s,name=%s,phone=%s, address=%s", poi.uid,  
  108. //                  poi.city, poi.name, poi.phoneNum, poi.address);  
  109. //          Log.d(TAG, detail); // 坐标为poi.location(LatLng结构)  
  110. //          }  
  111.         } else if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {  
  112.             // 当输入关键字在本市没有找到,但在其他城市找到时,返回包含该关键字信息的城市列表  
  113.             String strInfo = "在";  
  114.             for (CityInfo cityInfo : result.getSuggestCityList()) {  
  115.                 strInfo += cityInfo.city + ",";  
  116.             }  
  117.             strInfo += "找到结果";  
  118.             Toast.makeText(this, strInfo, Toast.LENGTH_LONG).show();  
  119.         }  
  120.     }  
  121.   
  122.     public void onGetPoiDetailResult(PoiDetailResult result) {  
  123.         if (result.error != SearchResult.ERRORNO.NO_ERROR) {  
  124.             Toast.makeText(this"抱歉,未找到结果", Toast.LENGTH_SHORT).show();  
  125.         } else {  
  126.             Log.d(TAG,  
  127.                     "name=" + result.getName() + ",address="  
  128.                             + result.getAddress() + ",detail_url="  
  129.                             + result.getDetailUrl() + ",shop_hours="  
  130.                             + result.getShopHours() + ",telephone="  
  131.                             + result.getTelephone() + ",price="  
  132.                             + result.getPrice() + ",type=" + result.getType()  
  133.                             + ",tag=" + result.getTag());  
  134.             Toast.makeText(this, result.getName() + ": " + result.getAddress(),  
  135.                     Toast.LENGTH_SHORT).show();  
  136.         }  
  137.     }  
  138.   
  139.     private class MyPoiOverlay extends PoiOverlay {  
  140.   
  141.         public MyPoiOverlay(BaiduMap baiduMap) {  
  142.             super(baiduMap);  
  143.         }  
  144.   
  145.         @Override  
  146.         public boolean onPoiClick(int index) {  
  147.             super.onPoiClick(index);  
  148.             PoiInfo poi = getPoiResult().getAllPoi().get(index);  
  149.             mPoiSearch.searchPoiDetail((new PoiDetailSearchOption()).poiUid(poi.uid));  
  150.             return true;  
  151.         }  
  152.     } 

高德地图

  1. // 以下主要是POI搜索用到的代码  
  2.     private PoiSearch mPoiSearch = null;  
  3.     private AutoCompleteTextView mKey = null;  
  4.     private EditText mScope = null;  
  5.     private Button btn_search, btn_nextpage, btn_cleardata;  
  6.     private ArrayAdapter<String> sugAdapter = null;  
  7.     private int load_Index = 0;  
  8.   
  9.     private void initMap() {  
  10.         mScope = (EditText) findViewById(R.id.poi_city);  
  11.         mKey = (AutoCompleteTextView) findViewById(R.id.poi_searchkey);  
  12.         btn_search = (Button) findViewById(R.id.search);  
  13.         btn_nextpage = (Button) findViewById(R.id.map_next_data);  
  14.         btn_cleardata = (Button) findViewById(R.id.map_clear_data);  
  15.         btn_search.setOnClickListener(this);  
  16.         btn_nextpage.setOnClickListener(this);  
  17.         btn_cleardata.setOnClickListener(this);  
  18.         sugAdapter = new ArrayAdapter<String>(this, R.layout.spinner_dropdown_item);  
  19.         mKey.setAdapter(sugAdapter);  
  20.   
  21.         // 当输入关键字变化时,动态更新建议列表  
  22.         mKey.addTextChangedListener(new TextWatcher() {  
  23.   
  24.             @Override  
  25.             public void afterTextChanged(Editable arg0) {  
  26.             }  
  27.   
  28.             @Override  
  29.             public void beforeTextChanged(CharSequence arg0, int arg1,  
  30.                     int arg2, int arg3) {  
  31.             }  
  32.   
  33.             @Override  
  34.             public void onTextChanged(CharSequence cs, int arg1, int arg2,  
  35.                     int arg3) {  
  36.                 if (cs.length() <= 0) {  
  37.                     return;  
  38.                 }  
  39.                 String city = mScope.getText().toString();  
  40.                 // 使用建议搜索服务获取建议列表,结果在onGetInputtips中更新  
  41.                 InputtipsQuery inputquery = new InputtipsQuery(cs.toString(), city);  
  42.                 Inputtips inputTips = new Inputtips(GaodeActivity.this, inputquery);  
  43.                 inputTips.setInputtipsListener(GaodeActivity.this);  
  44.                 inputTips.requestInputtipsAsyn();  
  45.             }  
  46.         });  
  47.     }  
  48.   
  49.     @Override  
  50.     public void onGetInputtips(List<Tip> tipList, int rCode) {  
  51.         if (rCode != 1000) {  
  52.             Toast.makeText(this"推荐文字错误代码是"+rCode, Toast.LENGTH_LONG).show();  
  53.         } else {  
  54.             sugAdapter.clear();  
  55.             for (Tip info : tipList) {  
  56.                 if (info.getName() != null) {  
  57.                     sugAdapter.add(info.getName());  
  58.                 }  
  59.             }  
  60.             sugAdapter.notifyDataSetChanged();  
  61.         }  
  62.     }  
  63.   
  64.     // 影响搜索按钮点击事件  
  65.     public void searchButtonProcess(View v) {  
  66.         Log.d(TAG, "editCity=" + mScope.getText().toString()  
  67.                 + ", editSearchKey=" + mKey.getText().toString()  
  68.                 + ", load_Index=" + load_Index);  
  69.         String keyword = mKey.getText().toString();  
  70.         if (search_method == SEARCH_CITY) {  
  71.             String city = mScope.getText().toString();  
  72.             PoiSearch.Query query = new PoiSearch.Query(keyword, null, city);  
  73.             query.setPageSize(10);  
  74.             query.setPageNum(load_Index);  
  75.             mPoiSearch = new PoiSearch(this, query);  
  76.             mPoiSearch.setOnPoiSearchListener(this);  
  77.             mPoiSearch.searchPOIAsyn();  
  78.         } else if (search_method == SEARCH_NEARBY) {  
  79.             LatLonPoint position = new LatLonPoint(m_latitude, m_longitude);  
  80.             int radius = Integer.parseInt(mScope.getText().toString());  
  81.             PoiSearch.Query query = new PoiSearch.Query(keyword, null"福州");  
  82.             query.setPageSize(10);  
  83.             query.setPageNum(load_Index);  
  84.             mPoiSearch = new PoiSearch(this, query);  
  85.             SearchBound bound = new SearchBound(position, radius);  
  86.             mPoiSearch.setBound(bound);  
  87.             mPoiSearch.setOnPoiSearchListener(this);  
  88.             mPoiSearch.searchPOIAsyn();  
  89.         }  
  90.     }  
  91.   
  92.     public void goToNextPage(View v) {  
  93.         load_Index++;  
  94.         searchButtonProcess(null);  
  95.     }  
  96.   
  97.     @Override  
  98.     public void onPoiSearched(PoiResult result, int rCode) {  
  99.         if (rCode != 1000) {  
  100.             Toast.makeText(this"POI错误代码是"+rCode, Toast.LENGTH_LONG).show();  
  101.         } else if (result == null || result.getQuery() == null) {  
  102.             Toast.makeText(this"未找到结果", Toast.LENGTH_LONG).show();  
  103.             return;  
  104.         } else {  
  105.             mMapLayer.clear();  
  106.             List<PoiItem> poiList = result.getPois();  
  107.             // 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息  
  108.             List<SuggestionCity> suggestionCities = result.getSearchSuggestionCitys();  
  109.             if (poiList!=null && poiList.size()>0) {  
  110.                 PoiOverlay poiOverlay = new PoiOverlay(mMapLayer, poiList);  
  111.                 //从地图上移除原POI信息  
  112.                 poiOverlay.removeFromMap();  
  113.                 //往地图添加新POI信息  
  114.                 poiOverlay.addToMap();  
  115.                 poiOverlay.zoomToSpan();  
  116.                 //给POI添加监听器。在点击POI时提示POI信息  
  117.                 mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() {  
  118.                     @Override  
  119.                     public boolean onMarkerClick(Marker marker) {  
  120.                         marker.showInfoWindow();  
  121.                         return true;  
  122.                     }  
  123.                 });  
  124. //              for (PoiItem poi : poiList) {  
  125. //                  String detail = String.format(  
  126. //                          "uid=%s,city=%s,name=%s,phone=%s, address=%s", poi.getPoiId(),  
  127. //                          poi.getCityName(), poi.getTitle(), poi.getTel(), poi.getAdName());  
  128. //                  Log.d(TAG, detail); // 坐标为poi.location(LatLng结构)  
  129. //              }  
  130.             } else if (suggestionCities != null && suggestionCities.size() > 0) {  
  131.                 String infomation = "推荐城市\n";  
  132.                 for (int i = 0; i < suggestionCities.size(); i++) {  
  133.                     SuggestionCity city = suggestionCities.get(i);  
  134.                     infomation += "城市名称:" + city.getCityName() + "城市区号:"  
  135.                             + city.getCityCode() + "城市编码:"  
  136.                             + city.getAdCode() + "\n";  
  137.                 }  
  138.                 Toast.makeText(this, infomation, Toast.LENGTH_LONG).show();  
  139.             } else {  
  140.                 Toast.makeText(this"结果记录数为0", Toast.LENGTH_LONG).show();  
  141.             }  
  142.             return;  
  143.         }  
  144.     }  
  145.   
  146.     @Override  
  147.     public void onPoiItemSearched(PoiItem paramPoiItem, int paramInt) {  
  148.         // TODO Auto-generated method stub  
  149.           
  150.     } 

测距、测面积

测量距离和测量面积是地图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进行测量的代码例子:
百度地图

  1. // 下面是在地图上添加绘图操作  
  2. private static int lineColor = 0x55FF0000;  
  3. private static int arcColor = 0xbb00FFFF;  
  4. private static int textColor = 0x990000FF;  
  5. private static int polygonColor = 0x77FFFF00;  
  6. private static int radius = 100;  
  7. private ArrayList<LatLng> posArray = new ArrayList<LatLng>();  
  8. boolean is_polygon = false;  
  9.   
  10. private void addDot(LatLng pos) {  
  11.     if (is_polygon == true && posArray.size() > 1  
  12.             && MapUtil.isInsidePolygon(pos, posArray) == true) {  
  13.         Log.d(TAG, "isInsidePolygon");  
  14.         LatLng centerPos = MapUtil.getCenterPos(posArray);  
  15.         OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff)  
  16.                 .fontSize(26).fontColor(textColor).text("标题")// .rotate(-30)  
  17.                 .position(centerPos);  
  18.         mMapLayer.addOverlay(ooText);  
  19.         return;  
  20.     }  
  21.     if (is_polygon == true) {  
  22.         Log.d(TAG, "is_polygon == true");  
  23.         posArray.clear();  
  24.         is_polygon = false;  
  25.     }  
  26.     boolean is_first = false;  
  27.     LatLng thisPos = pos;  
  28.     if (posArray.size() > 0) {  
  29.         LatLng firstPos = posArray.get(0);  
  30.         int distance = (int) Math.round(MapUtil.getShortDistance(  
  31.                 thisPos.longitude, thisPos.latitude, firstPos.longitude,  
  32.                 firstPos.latitude));  
  33.         //多次点击起点,要忽略之  
  34.         if (posArray.size()==1 && distance<=0) {  
  35.             return;  
  36.         } else if (posArray.size() > 1) {  
  37.             LatLng lastPos = posArray.get(posArray.size()-1);  
  38.             int lastDistance = (int) Math.round(MapUtil.getShortDistance(  
  39.                     thisPos.longitude, thisPos.latitude, lastPos.longitude,  
  40.                     lastPos.latitude));  
  41.             //重复响应当前位置的点击,要忽略之  
  42.             if (lastDistance <= 0) {  
  43.                 return;  
  44.             }  
  45.         }  
  46.         if (distance < radius * 2) {  
  47.             thisPos = firstPos;  
  48.             is_first = true;  
  49.         }  
  50.         Log.d(TAG, "distance="+distance+", radius="+radius+", is_first="+is_first);  
  51.   
  52.         // 画直线  
  53.         LatLng lastPos = posArray.get(posArray.size() - 1);  
  54.         List<LatLng> points = new ArrayList<LatLng>();  
  55.         points.add(lastPos);  
  56.         points.add(thisPos);  
  57.         OverlayOptions ooPolyline = new PolylineOptions().width(2)  
  58.                 .color(lineColor).points(points);  
  59.         mMapLayer.addOverlay(ooPolyline);  
  60.   
  61.         // 下面计算两点之间距离  
  62.         distance = (int) Math.round(MapUtil.getShortDistance(  
  63.                 thisPos.longitude, thisPos.latitude, lastPos.longitude,  
  64.                 lastPos.latitude));  
  65.         String disText = "";  
  66.         if (distance > 1000) {  
  67.             disText = Math.round(distance * 10 / 1000) / 10d + "公里";  
  68.         } else {  
  69.             disText = distance + "米";  
  70.         }  
  71.         LatLng llText = new LatLng(  
  72.                 (thisPos.latitude + lastPos.latitude) / 2,  
  73.                 (thisPos.longitude + lastPos.longitude) / 2);  
  74.         OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff)  
  75.                 .fontSize(24).fontColor(textColor).text(disText)// .rotate(-30)  
  76.                 .position(llText);  
  77.         mMapLayer.addOverlay(ooText);  
  78.     }  
  79.     if (is_first != true) {  
  80.         // 画圆圈  
  81.         OverlayOptions ooCircle = new CircleOptions().fillColor(lineColor)  
  82.                 .center(thisPos).stroke(new Stroke(20xAAFF0000)).radius(radius);  
  83.         mMapLayer.addOverlay(ooCircle);  
  84.         // 画图片标记  
  85.         BitmapDescriptor bitmapDesc = BitmapDescriptorFactory  
  86.                 .fromResource(R.drawable.icon_geo);  
  87.         OverlayOptions ooMarker = new MarkerOptions().draggable(false)  
  88.                 .visible(true).icon(bitmapDesc).position(thisPos);  
  89.         mMapLayer.addOverlay(ooMarker);  
  90.         mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() {  
  91.             @Override  
  92.             public boolean onMarkerClick(Marker marker) {  
  93.                 LatLng markPos = marker.getPosition();  
  94.                 addDot(markPos);  
  95.                 return true;  
  96.             }  
  97.         });  
  98.     } else {  
  99.         Log.d(TAG, "posArray.size()="+posArray.size());  
  100.         //可能存在地图与标记同时响应点击事件的情况  
  101.         if (posArray.size() < 3) {  
  102.             posArray.clear();  
  103.             is_polygon = false;  
  104.             return;  
  105.         }  
  106.         // 画多边形  
  107.         OverlayOptions ooPolygon = new PolygonOptions().points(posArray)  
  108.                 .stroke(new Stroke(10xFF00FF00))  
  109.                 .fillColor(polygonColor);  
  110.         mMapLayer.addOverlay(ooPolygon);  
  111.         is_polygon = true;  
  112.   
  113.         // 下面计算多边形的面积  
  114.         LatLng centerPos = MapUtil.getCenterPos(posArray);  
  115.         double area = Math.round(MapUtil.getArea(posArray));  
  116.         String areaText = "";  
  117.         if (area > 1000000) {  
  118.             areaText = Math.round(area * 100 / 1000000) / 100d + "平方公里";  
  119.         } else {  
  120.             areaText = (int) area + "平方米";  
  121.         }  
  122.         OverlayOptions ooText = new TextOptions().bgColor(0x00ffffff)  
  123.                 .fontSize(26).fontColor(textColor).text(areaText)// .rotate(-30)  
  124.                 .position(centerPos);  
  125.         mMapLayer.addOverlay(ooText);  
  126.     }  
  127.     posArray.add(thisPos);  
  128.     if (posArray.size() >= 3) {  
  129.         // 画弧线  
  130.         OverlayOptions ooArc = new ArcOptions()  
  131.                 .color(arcColor)  
  132.                 .width(2)  
  133.                 .points(posArray.get(posArray.size() - 1),  
  134.                         posArray.get(posArray.size() - 2),  
  135.                         posArray.get(posArray.size() - 3));  
  136.         mMapLayer.addOverlay(ooArc);  
  137.     }  
  138. }  
  139.   
  140. @Override  
  141. public void onMapClick(LatLng arg0) {  
  142.     addDot(arg0);  
  143. }  
  144.   
  145. @Override  
  146. public boolean onMapPoiClick(MapPoi arg0) {  
  147.     addDot(arg0.getPosition());  
  148.     return false;  

高德地图

  1. // 下面是在地图上添加绘图操作  
  2. private static int lineColor = 0x55FF0000;  
  3. private static int arcColor = 0xbb00FFFF;  
  4. private static int textColor = 0x990000FF;  
  5. private static int polygonColor = 0x77FFFF00;  
  6. private static int radius = 100;  
  7. private ArrayList<LatLng> posArray = new ArrayList<LatLng>();  
  8. boolean is_polygon = false;  
  9.   
  10. private void addDot(LatLng pos) {  
  11.     if (is_polygon == true && posArray.size() > 1  
  12.             && MapUtil.isInsidePolygon(pos, posArray) == true) {  
  13.         Log.d(TAG, "isInsidePolygon");  
  14.         LatLng centerPos = MapUtil.getCenterPos(posArray);  
  15.         TextOptions ooText = new TextOptions().backgroundColor(0x00ffffff)  
  16.                 .fontSize(26).fontColor(textColor).text("标题")// .rotate(-30)  
  17.                 .position(centerPos);  
  18.         mMapLayer.addText(ooText);  
  19.         return;  
  20.     }  
  21.     if (is_polygon == true) {  
  22.         Log.d(TAG, "is_polygon == true");  
  23.         posArray.clear();  
  24.         is_polygon = false;  
  25.     }  
  26.     boolean is_first = false;  
  27.     LatLng thisPos = pos;  
  28.     if (posArray.size() > 0) {  
  29.         LatLng firstPos = posArray.get(0);  
  30.         int distance = (int) Math.round(MapUtil.getShortDistance(  
  31.                 thisPos.longitude, thisPos.latitude, firstPos.longitude,  
  32.                 firstPos.latitude));  
  33.         //多次点击起点,要忽略之  
  34.         if (posArray.size()==1 && distance<=0) {  
  35.             return;  
  36.         } else if (posArray.size() > 1) {  
  37.             LatLng lastPos = posArray.get(posArray.size()-1);  
  38.             int lastDistance = (int) Math.round(MapUtil.getShortDistance(  
  39.                     thisPos.longitude, thisPos.latitude, lastPos.longitude,  
  40.                     lastPos.latitude));  
  41.             //重复响应当前位置的点击,要忽略之  
  42.             if (lastDistance <= 0) {  
  43.                 return;  
  44.             }  
  45.         }  
  46.         if (distance < radius * 2) {  
  47.             thisPos = firstPos;  
  48.             is_first = true;  
  49.         }  
  50.         Log.d(TAG, "distance="+distance+", radius="+radius+", is_first="+is_first);  
  51.   
  52.         // 画直线  
  53.         LatLng lastPos = posArray.get(posArray.size() - 1);  
  54.         List<LatLng> points = new ArrayList<LatLng>();  
  55.         points.add(lastPos);  
  56.         points.add(thisPos);  
  57.         PolylineOptions ooPolyline = new PolylineOptions().width(2)  
  58.                 .color(lineColor).addAll(points);  
  59.         mMapLayer.addPolyline(ooPolyline);  
  60.   
  61.         // 下面计算两点之间距离  
  62.         distance = (int) Math.round(MapUtil.getShortDistance(  
  63.                 thisPos.longitude, thisPos.latitude, lastPos.longitude,  
  64.                 lastPos.latitude));  
  65.         String disText = "";  
  66.         if (distance > 1000) {  
  67.             disText = Math.round(distance * 10 / 1000) / 10d + "公里";  
  68.         } else {  
  69.             disText = distance + "米";  
  70.         }  
  71.         LatLng llText = new LatLng(  
  72.                 (thisPos.latitude + lastPos.latitude) / 2,  
  73.                 (thisPos.longitude + lastPos.longitude) / 2);  
  74.         TextOptions ooText = new TextOptions().backgroundColor(0x00ffffff)  
  75.                 .fontSize(24).fontColor(textColor).text(disText)// .rotate(-30)  
  76.                 .position(llText);  
  77.         mMapLayer.addText(ooText);  
  78.     }  
  79.     if (is_first != true) {  
  80.         // 画圆圈  
  81.         CircleOptions ooCircle = new CircleOptions().fillColor(lineColor)  
  82.                 .center(thisPos).strokeWidth(2).strokeColor(0xAAFF0000).radius(radius);  
  83.         mMapLayer.addCircle(ooCircle);  
  84.         // 画图片标记  
  85.         BitmapDescriptor bitmapDesc = BitmapDescriptorFactory  
  86.                 .fromResource(R.drawable.icon_geo);  
  87.         MarkerOptions ooMarker = new MarkerOptions().draggable(false)  
  88.                 .visible(true).icon(bitmapDesc).position(thisPos);  
  89.         mMapLayer.addMarker(ooMarker);  
  90.         mMapLayer.setOnMarkerClickListener(new OnMarkerClickListener() {  
  91.             @Override  
  92.             public boolean onMarkerClick(Marker marker) {  
  93.                 LatLng markPos = marker.getPosition();  
  94.                 addDot(markPos);  
  95.                 marker.showInfoWindow();  
  96.                 return true;  
  97.             }  
  98.         });  
  99.     } else {  
  100.         Log.d(TAG, "posArray.size()="+posArray.size());  
  101.         //可能存在地图与标记同时响应点击事件的情况  
  102.         if (posArray.size() < 3) {  
  103.             posArray.clear();  
  104.             is_polygon = false;  
  105.             return;  
  106.         }  
  107.         // 画多边形  
  108.         PolygonOptions ooPolygon = new PolygonOptions().addAll(posArray)  
  109.                 .strokeColor(0xFF00FF00).strokeWidth(1)  
  110.                 .fillColor(polygonColor);  
  111.         mMapLayer.addPolygon(ooPolygon);  
  112.         is_polygon = true;  
  113.   
  114.         // 下面计算多边形的面积  
  115.         LatLng centerPos = MapUtil.getCenterPos(posArray);  
  116.         double area = Math.round(MapUtil.getArea(posArray));  
  117.         String areaText = "";  
  118.         if (area > 1000000) {  
  119.             areaText = Math.round(area * 100 / 1000000) / 100d + "平方公里";  
  120.         } else {  
  121.             areaText = (int) area + "平方米";  
  122.         }  
  123.         TextOptions ooText = new TextOptions().backgroundColor(0x00ffffff)  
  124.                 .fontSize(26).fontColor(textColor).text(areaText)// .rotate(-30)  
  125.                 .position(centerPos);  
  126.         mMapLayer.addText(ooText);  
  127.     }  
  128.     posArray.add(thisPos);  
  129.     if (posArray.size() >= 3) {  
  130.         // 画弧线  
  131.         ArcOptions ooArc = new ArcOptions()  
  132.                 .strokeColor(arcColor)  
  133.                 .strokeWidth(2)  
  134.                 .point(posArray.get(posArray.size() - 1),  
  135.                         posArray.get(posArray.size() - 2),  
  136.                         posArray.get(posArray.size() - 3));  
  137.         mMapLayer.addArc(ooArc);  
  138.     }  
  139. }  
  140.   
  141. @Override  
  142. public void onMapClick(LatLng arg0) {  
  143.     addDot(arg0);  

点此查看Android开发笔记的完整目录


此文章转载自:http://blog.csdn.net/aqi00/article/details/51555670


0 0