Android practice-Location-Based Services (get the longitude and latitude of your location + Baidu map) and android longitude and latitude

Source: Internet
Author: User

Android practice-Location-Based Services (get the longitude and latitude of your location + Baidu map) and android longitude and latitude

The LocationManager class must be used for implementation. The following code is used:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


The. java code is as follows:

package org.lxh.demo;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Hello extends Activity {
private TextView textView;
private LocationManager locationManager;
private String provider;

public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState); // Lifecycle method

super.setContentView (R.layout.main); // Set the layout manager to be used
Log.d ("111111", "4444444");
textView = (TextView) findViewById (R.id.edit);
locationManager = (LocationManager) getSystemService (Context.LOCATION_SERVICE);
List <String> providerList = locationManager.getProviders (true); // Get all available location providers
if (providerList.contains (LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains (LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
Log.d ("111111", "3333333");

} else {
Toast.makeText (this, "No location provider to use!",
Toast.LENGTH_SHORT) .show ();
return;
}
Location location = locationManager.getLastKnownLocation (provider);
if (location! = null) {
showLocation (location);
}
locationManager.requestLocationUpdates (provider, 5000, 1,
locationListener);

}

private void showLocation (Location location) {
String crrrentPositionString = "latitude is" + location.getLatitude ()
+ "\ n" + "longitude is" + location.getLongitude ();
textView.setText (crrrentPositionString);

}

LocationListener locationListener = new LocationListener () {

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

}

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

}

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

}

public void onLocationChanged (Location location) {
showLocation (location); // Update the current device information
Log.d ("111111", "222222");

}
};

protected void onDestroy () {
super .onDestroy ();
if (locationManager! = null) {
locationManager.removeUpdates (locationListener);
}
};
}


The AndroidManifest. xml Code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest 
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="org.lxh.demo" 
	android:versionCode="1" 
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/><!-- 声明权限 -->
	<application 
		android:icon="@drawable/icon" 
		android:label="@string/app_name">
		<activity 
			android:name=".Hello" 
			android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
	
</manifest>


Run the instance to display your current longitude and latitude. The following describes how to use Baidu map:

First, you need to apply for an API Key. You can use Baidu to download the jar package after completing all the operations:


Import the SDK:


Then set the layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.baidu.mapapi.map.MapView
        android:id="@+id/map_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />

</LinearLayout>


Then modify the MainActivity. java file:

package com.example.baidumaptest;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class MainActivity extends Activity {

private BMapManager manager;

private MapView mapView;

private LocationManager locationManager;

private String provider;

@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
manager = new BMapManager (this);
// API Key needs to be replaced with your own
manager.init ("SHVPoTtIpzfonPD3HCkc5sIt", null);
setContentView (R.layout.activity_main);
mapView = (MapView) findViewById (R.id.map_view);
mapView.setBuiltInZoomControls (true);
locationManager = (LocationManager) getSystemService (Context.LOCATION_SERVICE);
// Get all available location providers
List <String> providerList = locationManager.getProviders (true);
if (providerList.contains (LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains (LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
} else {
// When no location provider is available, pop up Toast to prompt the user
Toast.makeText (this, "No location provider to use",
Toast.LENGTH_SHORT) .show ();
return;
}
Location location = locationManager.getLastKnownLocation (provider);
if (location! = null) {
navigateTo (location);
}
}

private void navigateTo (Location location) {
MapController controller = mapView.getController ();
// Set the zoom level
controller.setZoom (16);
GeoPoint point = new GeoPoint ((int) (location.getLatitude () * 1E6),
(int) (location.getLongitude () * 1E6));
// Set the center point of the map
controller.setCenter (point);
MyLocationOverlay myLocationOverlay = new MyLocationOverlay (mapView);
LocationData locationData = new LocationData ();
// specify my location
locationData.latitude = location.getLatitude ();
locationData.longitude = location.getLongitude ();
myLocationOverlay.setData (locationData);
mapView.getOverlays (). add (myLocationOverlay);
// refresh for the new overlay to take effect
mapView.refresh ();
PopupOverlay pop = new PopupOverlay (mapView, new PopupClickListener () {
@Override
public void onClickedPopup (int index) {
// Click event of corresponding image
Toast.makeText (MainActivity.this,
"You clicked button" + index, Toast.LENGTH_SHORT)
.show ();
}
});
// create a Bitmap array of length 3
Bitmap [] bitmaps = new Bitmap [3];
try {
// read three pictures into memory
bitmaps [0] = BitmapFactory.decodeResource (getResources (),
R.drawable.left);
bitmaps [1] = BitmapFactory.decodeResource (getResources (),
R.drawable.middle);
bitmaps [2] = BitmapFactory.decodeResource (getResources (),
R.drawable.right);
} catch (Exception e) {
e.printStackTrace ();
}
pop.showPopup (bitmaps, point, 18);
}

@Override
protected void onDestroy () {
mapView.destroy ();
if (manager! = null) {
manager.destroy ();
manager = null;
}
super.onDestroy ();
}

@Override
protected void onPause () {
mapView.onPause ();
if (manager! = null) {
manager.stop ();
}
super.onPause ();
}

@Override
protected void onResume () {
mapView.onResume ();
if (manager! = null) {
manager.start ();
}
super.onResume ();
}

}


Configure the AndroidManifest. xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.baidumaptest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.baidumaptest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Running instance:


 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.