顯示具有 定位 標籤的文章。 顯示所有文章
顯示具有 定位 標籤的文章。 顯示所有文章

2016年5月8日 星期日

iOS Swift GPS 定位

定位功能

1.Main.storyboard拉label

2.在Info.plist的 Information Property List點"+",
在左邊key輸入"NSLocationWhenInUseUsageDescription"
在右邊Value輸入"The application uses this information to show you your location"

3.ViewController.swift

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    
    
    @IBOutlet weak var lblLat: UILabel!
    @IBOutlet weak var lblLon: UILabel!
    @IBOutlet weak var lblHorizontal: UILabel!
    @IBOutlet weak var lblAltitude: UILabel!
    @IBOutlet weak var lblVertical: UILabel!
    @IBOutlet weak var lblDistance: UILabel!
    
    var locationManager: CLLocationManager = CLLocationManager()
    var startLocation: CLLocation!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        
        startLocation = CLLocation(latitude: 22.6657786, longitude: 120.3033831) //目標緯度經度
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //定位資訊
        let latestLocation: AnyObject = locations[locations.count - 1]
        
        lblLat.text = String(format: "%.4f", latestLocation.coordinate.latitude) //緯度
        lblLon.text = String(format: "%.4f", latestLocation.coordinate.longitude) //經度
        lblHorizontal.text = String(format: "%.4f", latestLocation.horizontalAccuracy) //水平精度
        lblAltitude.text = String(format: "%.4f", latestLocation.altitude) //海拔高度
        lblVertical.text = String(format: "%.4f", latestLocation.verticalAccuracy) //垂直精度
        
        let distanceBetween: CLLocationDistance =
            latestLocation.distanceFromLocation(startLocation) //計算startLocation與latestLocation距離
        
        lblDistance.text = String(format: "%.2f", distanceBetween) //距離 公尺
    }
    
    func locationManager(manager: CLLocationManager,
                         didFailWithError error: NSError) {
        
    }
    
}



3.參考連結:
http://www.techotopia.com/index.php/A_Swift_Example_iOS_8_Location_Application
http://stackoverflow.com/questions/29931302/initialize-a-cllocation-object-in-swift-with-latitude-and-longitude

2014年6月9日 星期一

Android GPS 定位 距離 偵測

開車照相偵測app都會偵測某個點有照相偵測機,然後發出警告,此app會用到GPS與Broadcast功能。需建立GPSService.java與GPSReceiver.java檔(與MainActivity.java同資料夾)
1.activity_main.xml
輸入接近目標的經緯度,打勾啟動

  
   
  
  
  
  

2.AndroidManifest.xml
加入GPSReceiver接收功能與GPSService廣播功能,VIBRATE手機震動功能,ACCESS_FINE_LOCATION定位功能。



        
            
                
            
        

        
3.MainActivity.java
 private EditText lat, lon;
 private CheckBox checkBox_service;
 private TextView output;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  lat = (EditText) findViewById(R.id.txtLat);
  lon = (EditText) findViewById(R.id.txtLong);
  checkBox_service = (CheckBox) findViewById(R.id.checkBox_service);
  output = (TextView) findViewById(R.id.output);
  if (checkBox_service.isChecked()) {
   start_Click(); //啟動功能
  } else {
   stop_Click(); //停止功能
  }
 }
 public void start_Click() {
  float latitude = Float.parseFloat(lat.getText().toString()); //取得輸入座標
  float longitude = Float.parseFloat(lon.getText().toString()); //取得輸入座標
  Intent intent = new Intent(this, GPSService.class); //送至GPSService.java
  intent.putExtra("LATITUDE", latitude); //發送座標至GPSService
  intent.putExtra("LONGITUDE", longitude); //發送座標至GPSService
  startService(intent);
  output.setText("服務啟動中");
 }

 public void stop_Click() {
  Intent intent = new Intent(this, GPSService.class);
  stopService(intent);
  output.setText("服務停止中");
 }
4.GPSService.java
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSService extends Service implements LocationListener {
 private LocationManager manager;
 private boolean isInArea;
 private double latitude, longitude;

 @Override
 public void onCreate() {

  manager = (LocationManager) getSystemService(LOCATION_SERVICE);
  manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 1,
    this);
  manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1,
    this);
  isInArea = false; //是否在範圍內
 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  try {
   latitude = (double) intent.getFloatExtra("LATITUDE1", 22.6297370f); //取得座標
   longitude = (double) intent.getFloatExtra("LONGITUDE1", 120.3278820f); //取得座標
  } catch (NullPointerException e) {
   Log.i("GPSService","NullPointException");
  }
  Log.d("GPSService", "lat/long: " + latitude + ": " + longitude);
  return START_STICKY;
 }

 @Override
 public void onDestroy() {
  manager.removeUpdates(this); //移除定位服務更新
 }

 @Override
 public void onLocationChanged(Location current) {
  // TODO Auto-generated method stub
  if (current == null)
   return;
  Location dest = new Location(current); //取得現在位置
  dest.setLatitude(latitude); //取得現在位置座標
  dest.setLongitude(longitude); //取得現在位置座標
  float distance = current.distanceTo(dest); //計算目標位置與現在位置距離
  if (distance < 1000.0) { //當目標小於1公里時
   if (isInArea == false) { //在區域內
    Intent intent = new Intent("android.broadcast.LOCATION"); //啟動廣播服務
    sendBroadcast(intent); //發送廣播
    isInArea = true; //是否在區域內:true
   }
  } else {
   isInArea = false; //是否在區域內:false
  }

 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onProviderEnabled(String provider) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onProviderDisabled(String provider) {
  // TODO Auto-generated method stub

 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }

}

5.GPSReceiver.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;

public class GPSReceiver extends BroadcastReceiver {
 static int id = 70000;
 @SuppressWarnings("deprecation")
 @Override
 public void onReceive(Context context, Intent intent) {
  //Notification
  NotificationManager notificationManager = (NotificationManager) context
    .getSystemService(android.content.Context.NOTIFICATION_SERVICE);

  Notification notification = new Notification(R.drawable.ic_launcher,
    "您已經接近目標", System.currentTimeMillis()); //跳出Notification訊息
  Intent newintent = new Intent(context, MainActivity.class);
  PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
    newintent, 0);
  notification.setLatestEventInfo(context, "再接近就要被拍了!!", null, contentIntent);

  notificationManager.notify(id++, notification);
  
  //手機震動
  Vibrator vibrator = (Vibrator) context
    .getSystemService(Context.VIBRATOR_SERVICE);
  vibrator.vibrate(500); // 半秒
 }
}

參考來源:
http://goo.gl/BbbtPe
http://hscc.cs.nctu.edu.tw/~lincyu/Android/Chapter7.pdf