Android下实现GPS定位服务

1.申请Google API Key,参考前面文章

2.实现GPS的功能需要使用模拟器进行经纬度的模拟设置,请参考前一篇文章进行设置

3.创建一个Build Target为Google APIs的项目

4.修改Androidmanifest文件:

 

  1. <uses-library android:name="com.google.android.maps" />  
  2. <uses-permission android:name="android.permission.INTERNET"/>  
  3.      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  
  4.      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  

 

5.修改main.xml文件

 

  1. <com.google.android.maps.MapView  
  2.     android:id="@+id/MapView01"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:apiKey="0f8FBFJliR7j_7aNwDxClBv6VW8O12V2Y21W_CQ"/>  

 

注意:这里的apiKey值请相应修改为自己的key值

6.代码清单:

 

 

  1. package com.hoo.android.LocationMap;  
  2. import java.io.IOException;  
  3. import java.util.List;  
  4. import java.util.Locale;  
  5. import android.content.Context;  
  6. import android.graphics.Bitmap;  
  7. import android.graphics.BitmapFactory;  
  8. import android.graphics.Canvas;  
  9. import android.graphics.Paint;  
  10. import android.graphics.Point;  
  11. import android.location.Address;  
  12. import android.location.Criteria;  
  13. import android.location.Geocoder;  
  14. import android.location.Location;  
  15. import android.location.LocationListener;  
  16. import android.location.LocationManager;  
  17. import android.os.Bundle;  
  18. import android.widget.TextView;  
  19. import com.google.android.maps.GeoPoint;  
  20. import com.google.android.maps.MapActivity;  
  21. import com.google.android.maps.MapController;  
  22. import com.google.android.maps.MapView;  
  23. import com.google.android.maps.Overlay;  
  24. public class ActivityLocationMap extends MapActivity   
  25. {  
  26.     public MapController mapController;  
  27.     public MyLocationOverlay myPosition;  
  28.     public MapView myMapView;  
  29.       
  30.     public void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.main);  
  33.         //取得LocationManager实例  
  34.         LocationManager locationManager;  
  35.         String context=Context.LOCATION_SERVICE;  
  36.         locationManager=(LocationManager)getSystemService(context);  
  37.         myMapView=(MapView)findViewById(R.id.MapView01);  
  38.         //取得MapController实例,控制地图  
  39.         mapController=myMapView.getController();  
  40.         //设置显示模式为街景模式  
  41.         myMapView.setStreetView(true);  
  42.           
  43.         //*************使用系统自带的控件放大缩小视图***************************  
  44.         //取得MapController对象(控制MapView)  
  45.         mapController = myMapView.getController();   
  46.         //设置地图支持设置模式  
  47.         myMapView.setEnabled(true);  
  48.         //设置地图支持点击  
  49.         myMapView.setClickable(true);     
  50.         //设置缩放控制,这里我们自己实现缩放菜单  
  51.         myMapView.displayZoomControls(true);    
  52.         myMapView.setBuiltInZoomControls(true);   
  53.         //*******************************************************************       
  54.         ////设置设置地图目前缩放大小倍数(从1到21)  
  55.         mapController.setZoom(17);  
  56.         //设置使用MyLocationOverlay来绘图  
  57.         myPosition=new MyLocationOverlay();  
  58.           
  59.         List<Overlay> overlays=myMapView.getOverlays();  
  60.         overlays.add(myPosition);  
  61.         //设置Criteria(标准服务商)的信息  
  62.         Criteria criteria =new Criteria();  
  63.         //*****设置服务商提供的精度要求,以供筛选提供商************************  
  64.         criteria.setAccuracy(Criteria.POWER_HIGH);//表明所要求的经纬度的精度              
  65.         criteria.setAltitudeRequired(false); //高度信息是否需要提供  
  66.         criteria.setBearingRequired(false);  //压力(气压?)信息是否需要提供  
  67.         criteria.setCostAllowed(false);  //是否会产生费用  
  68.         criteria.setPowerRequirement(Criteria.POWER_MEDIUM);//最大需求标准  
  69.         //*****************************************************  
  70.         //取得效果最好的criteria  
  71.         String provider=locationManager.getBestProvider(criteria, true);  
  72.         //得到坐标相关的信息  
  73.         Location location=locationManager.getLastKnownLocation(provider);  
  74.         //更新位置信息  
  75.         updateWithNewLocation(location);  
  76.         //注册一个周期性的更新,3000ms更新一次,0代表最短距离  
  77.         //locationListener用来监听定位信息的改变(OnLocationChanged)  
  78.         locationManager.requestLocationUpdates(provider, 30000,locationListener);  
  79.     }  
  80.       
  81.     //更新位置信息  
  82.     private void updateWithNewLocation(Location location)   
  83.     {  
  84.         String latLongString; //声明经纬度的字符串  
  85.         TextView myLocationText = (TextView)findViewById(R.id.TextView01);  
  86.         //初始化地址为没有找到,便于处理特殊情况  
  87.         String addressString="没有找到地址/n";  
  88.         if(location!=null)  
  89.         {  
  90.             //****************获取当前的经纬度,并定位到目标*************************  
  91.             //为绘制标志的类设置坐标  
  92.             myPosition.setLocation(location);  
  93.             //取得经度和纬度  
  94.             Double geoLat=location.getLatitude()*1E6;  
  95.             Double geoLng=location.getLongitude()*1E6;  
  96.             //将其转换为int型  
  97.             GeoPoint point=new GeoPoint(geoLat.intValue(),geoLng.intValue());  
  98.             //定位到指定坐标  
  99.             mapController.animateTo(point);  
  100.             //*********************************************************************  
  101.             double lat=location.getLatitude();  //获得经纬度  
  102.             double lng=location.getLongitude();  
  103.             latLongString="经度:"+lat+"/n纬度:"+lng;   //设置经纬度字符串  
  104.               
  105.            // double latitude=location.getLatitude();  
  106.             //double longitude=location.getLongitude();  
  107.             //根据地理位置来确定编码  
  108.             Geocoder gc=new Geocoder(this,Locale.getDefault());  
  109.             try  
  110.             {  
  111.                 //取得地址相关的一些信息:经度、纬度  
  112.                 List<Address> addresses=gc.getFromLocation(lat, lng,1);  
  113.                 StringBuilder sb=new StringBuilder();  
  114.                 if(addresses.size()>0)  
  115.                 {  
  116.                     Address address=addresses.get(0);  
  117.                     for(int i=0;i<address.getMaxAddressLineIndex()-1;i++)  
  118.                         sb.append(address.getAddressLine(i)).append(",");                       
  119.                         //获得地址sb.append(address.getLocality()).append("/n");  
  120.                         //获得邮编sb.append(address.getPostalCode()).append("/n");  
  121.                         sb.append(address.getCountryName());  
  122.                         addressString=sb.toString();  
  123.                 }  
  124.             }catch(IOException e){}  
  125.         }  
  126.         else  
  127.         {  
  128.             latLongString="没有找到坐标./n";  
  129.         }  
  130.         //显示  
  131.         myLocationText.setText("您当前的位置如下:/n"+latLongString+"/n"+addressString);  
  132.     }  
  133.     //监听位置信息的改变  
  134.     private final LocationListener locationListener=new LocationListener()  
  135.     {  
  136.         //当坐标改变时触发此函数  
  137.         public void onLocationChanged(Location location)  
  138.         {  
  139.             updateWithNewLocation(location);  
  140.         }  
  141.         //Provider被disable时触发此函数,比如GPS被关闭   
  142.         public void onProviderDisabled(String provider)  
  143.         {  
  144.             updateWithNewLocation(null);  
  145.         }  
  146.         //Provider被enable时触发此函数,比如GPS被打开  
  147.         public void onProviderEnabled(String provider){}  
  148.         //Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数  
  149.         public void onStatusChanged(String provider,int status,Bundle extras){}  
  150.     };  
  151.     //方法默认是true,服务器所知的状态列信息是否需要显示  
  152.     protected boolean isRouteDisplayed()  
  153.     {  
  154.         return false;  
  155.     }  
  156.       
  157.     class MyLocationOverlay extends Overlay  
  158.     {  
  159.         Location mLocation;  
  160.         //在更新坐标,以便画图  
  161.         public void setLocation(Location location)  
  162.         {  
  163.             mLocation = location;  
  164.         }  
  165.         @Override  
  166.         public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)  
  167.         {  
  168.             super.draw(canvas, mapView, shadow);              
  169.             Paint paint = new Paint();  
  170.             Point myScreenCoords = new Point();  
  171.             // 将经纬度转换成实际屏幕坐标  
  172.             GeoPoint tmpGeoPoint = new GeoPoint((int)(mLocation.getLatitude()*1E6),(int)(mLocation.getLongitude()*1E6));      
  173.             mapView.getProjection().toPixels(tmpGeoPoint, myScreenCoords);  
  174.             //*********paint相关属性设置*********  
  175.             paint.setStrokeWidth(0);//文  
  176.             paint.setARGB(25525500);  
  177.             paint.setStyle(Paint.Style.STROKE);  
  178.             //***********************************  
  179.             Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.green_dot);  
  180.             canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);  
  181.             canvas.drawText("您目前的位置", myScreenCoords.x, myScreenCoords.y, paint);  
  182.             return true;  
  183.         }  
  184.     }  
  185. }  

 

代码参考网络,加以修改优化,谢谢

7.程序运行截图,前提是在命令行下输入geo fix 121.5 31.24(定位到上海东方明珠),在命令行下可以输入其他坐标,系统会根据坐标显示其他位置,如接着输入geo fix 113.325 23.113(定位到广州海心沙),不知为什么输入坐标的时候经常会不识别,有时能够成功而有时不行,郁闷,求解……

原文地址:https://www.cnblogs.com/Free-Thinker/p/3606475.html