Arcgis For Android之GPS定位实现

翻开以前做的东西,看了看,很多从逻辑上比较乱,对之做了修改,完成后实现的效果为:

MapActivity源代码如下:

package com.lzugis.map;

import java.io.File;
import java.util.Iterator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISLocalTiledLayer;
import com.esri.android.runtime.ArcGISRuntime;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.lzugis.tool.ZoomCtrl;

public class MapActivity extends Activity {
	private static File dataFile;
	private static String dirName;
	private static String filename;	
	
	private LocationListener locationListener = new LocationListener(){
  		/**
         * 位置信息变化时触发
         */
    	public void onLocationChanged(Location location) {
			markLocation(location);
		}
    	/**
         * 状态改变时调用
         */
		public void onStatusChanged(String provider, int status, Bundle extras) 
		{
			switch (status) {
            //GPS状态为可见时
            case LocationProvider.AVAILABLE:
            	showToast("当前GPS状态为可见状态");
                Log.i("TAG", "当前GPS状态为可见状态");
                break;
            //GPS状态为服务区外时
            case LocationProvider.OUT_OF_SERVICE:
            	showToast("当前GPS状态为服务区外状态");
                Log.i("TAG", "当前GPS状态为服务区外状态");
                break;
            //GPS状态为暂停服务时
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
            	showToast("当前GPS状态为暂停服务状态");
                Log.i("TAG", "当前GPS状态为暂停服务状态");
                break;
            }
		}	    	
		/**
         * GPS开启时触发
         */
		public void onProviderEnabled(String provider) 
		{
			showToast("GPS打开");
			Location location=locMag.getLastKnownLocation(provider);
			markLocation(location);
		}
		/**
         * GPS禁用时触发
         */
		public void onProviderDisabled(String provider) 
		{
			showToast("GPS已关闭");
		}
	};
	
	MapView mapview;
	ArcGISLocalTiledLayer local;
	ZoomCtrl zoomCtrl;
	GraphicsLayer gLayerGps;
	
	Button btnPosition;
	Toast toast;
	LocationManager locMag;
	Location loc ;	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_map);		
        //去除水印
        ArcGISRuntime.setClientId("1eFHW78avlnRUPHm");
        
        //要定位在地图中的位置,需要知道当前位置,而当前位置有Location对象决定,
        //但是,Location对象又需要LocationManager对象来创建。
        //创建LocationManager的唯一方法
        locMag = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        
        mapview = (MapView)findViewById(R.id.map);		
        dataFile = Environment.getExternalStorageDirectory();
        dirName = this.getResources().getString(R.string.offline_dir);
	filename = this.getResources().getString(R.string.local_tpk);
	    
	String basemap = "file://"+dataFile + File.separator +dirName + File.separator + filename;
    	local = new ArcGISLocalTiledLayer(basemap);
    	mapview.addLayer(local);
    	
    	//放大与缩小
    	zoomCtrl = (ZoomCtrl) findViewById(R.id.ZoomControl);
    	zoomCtrl.setMapView(mapview);
    	
    	gLayerGps = new GraphicsLayer();
	    mapview.addLayer(gLayerGps);
	    
	  	    
	    btnPosition=(Button)findViewById(R.id.btnPosition);
	    btnPosition.setOnClickListener(new OnClickListener(){
	    	public void onClick(View v) {
	    		//判断GPS是否正常启动
	            if(!locMag.isProviderEnabled(LocationManager.GPS_PROVIDER)){
	                showToast("请开启GPS导航...");
	                //返回开启GPS导航设置界面
	                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
	                startActivityForResult(intent,0); 
	                return;
	            }
	            Location location= locMag.getLastKnownLocation(LocationManager.GPS_PROVIDER);  
	            markLocation(location);
	            locMag.addGpsStatusListener(listener);
	    		locMag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
	    	}			
	    });
    }
    
    //状态监听
    GpsStatus.Listener listener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {
            switch (event) {
            //第一次定位
            case GpsStatus.GPS_EVENT_FIRST_FIX:
                Log.i("TAG", "第一次定位");
                break;
            //卫星状态改变
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                Log.i("TAG", "卫星状态改变");
                //获取当前状态
                GpsStatus gpsStatus=locMag.getGpsStatus(null);
                //获取卫星颗数的默认最大值
                int maxSatellites = gpsStatus.getMaxSatellites();
                //创建一个迭代器保存所有卫星 
                Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                int count = 0;     
                while (iters.hasNext() && count <= maxSatellites) {     
                    GpsSatellite s = iters.next();     
                    count++;     
                }   
                System.out.println("搜索到:"+count+"颗卫星");
                break;
            //定位启动
            case GpsStatus.GPS_EVENT_STARTED:
                Log.i("TAG", "定位启动");
                break;
            //定位结束
            case GpsStatus.GPS_EVENT_STOPPED:
                Log.i("TAG", "定位结束");
                break;
            }
        };
    };
    
    private void markLocation(Location location)
	{
    	if(location!=null){
	    	Log.i("TAG", "时间:"+location.getTime()); 
	        Log.i("TAG", "经度:"+location.getLongitude()); 
	        Log.i("TAG", "纬度:"+location.getLatitude()); 
	        Log.i("TAG", "海拔:"+location.getAltitude()); 
			double locx = location.getLongitude();
			double locy = location.getLatitude();
			ShowPointOnMap(locx,locy);
    	}
	}
    
    public void ShowPointOnMap(double lon,double lat){
		//清空定位图层
		gLayerGps.removeAll(); 
		//接收到的GPS的信号X(lat),Y(lon)
		double locx = lon;
		double locy = lat;
		Point wgspoint = new Point(locx, locy);  
		Point mapPoint = (Point) GeometryEngine.project(wgspoint,SpatialReference.create(4326),mapview.getSpatialReference());
		//图层的创建
//		Graphic graphic = new Graphic(mapPoint,new SimpleMarkerSymbol(Color.RED,18,STYLE.CIRCLE));
		PictureMarkerSymbol pms =  new PictureMarkerSymbol(this.getResources().getDrawable(
				R.drawable.location));
		Graphic graphic = new Graphic(mapPoint,pms);
		gLayerGps.addGraphic(graphic);
	}
    
    private void showToast(String msg)
	{  
        if(toast == null)
        {  
        	toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);  
        }
        else
        {  
        	toast.setText(msg);  
        	toast.setDuration(Toast.LENGTH_SHORT);
        }  
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.show();  
    } 

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	@Override
	protected void onPause() {
		super.onPause();
		mapview.pause();
	}
	@Override
	protected void onResume() {
		super.onResume();
		mapview.unpause();
	}
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏developerHaoz 的安卓之旅

手把手教你从零开始做一个好看的 APP - Day four

本文为 手把手教你从零开始做一个好看的 APP - Day four ,如果想看该系列的其他文章,请点击以下连接

912
来自专栏增长技术

App Intro相关

##How to use Add this to your build.gradle:

762
来自专栏向治洪

android wheelview实现三级城市选择

很早之前看淘宝就有了ios那种的城市选择控件,当时也看到网友有分享,不过那个写的很烂,后来(大概是去年吧),我们公司有这么一个项目,当时用的还是网上比较流行的那...

4196
来自专栏浅探ARKit

ARKit同时检测水平平面和竖直平面

ARKit1.5里,新增了检测竖直平面的功能。为此特意写一个demo。 下面是效果图: [IMG_3728.PNG] 和之前的水平平面相比 其实就是把多一个属性...

41510
来自专栏肖蕾的博客

自定义BaseAdapter完美解决ListView异常:java.lang.IllegalStateException这是代码使用方法原理另外

1428
来自专栏何俊林

直播项目之仿全民TV(已开源)

前言:成印昨天发布了他最近闭关10天,开发的一个直播开源项目,我体验了下,觉得还不错,推荐给大家,点击文末【阅读原文】,可访问项目的github地址,觉得不错,...

3398
来自专栏编程之路

羊皮书APP(Android版)开发系列(十)Android开发常用工具类

1161
来自专栏Android开发指南

11.菜单界面、详情界面

2907
来自专栏向治洪

RecyclerView 实现横向滚动效果

我相信很久以前,大家在谈横向图片轮播是时候,优先会选择具有HorizontalScrollView效果和ViewPager来做,不过自从Google大会之后,系...

4016
来自专栏Sorrower的专栏

界面无小事(二): 让RecyclerView展示更多不同视图

1162

扫码关注云+社区

领取腾讯云代金券