2013-04-14 146 views
13

我正在創建一個谷歌地圖視圖的應用程序,我希望這個應用程序能夠檢測用戶的當前位置,並在地圖上顯示經緯度和長度,但所有我可以做的直到現在是谷歌地圖的顯示和當前位置的檢測,沒有任何標記顯示,也沒有任何文字出現顯示緯度和長度安卓+谷歌地圖api v2 +當前位置

我沒有添加標記,直到現在,因爲我不知道在哪裏把它放在代碼和最佳做法是什麼

任何人都可以幫助我? 這是該代碼:

清單文件

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

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="16" /> 

    <permission 
     android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 

    <uses-permission android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="in.wptrafficanalyzer.locationgooglemapv2demo.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> 

     <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="API KEY" /> 
    </application> 

</manifest> 

xml文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

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

    <fragment 
     android:id="@+id/map" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     class="com.google.android.gms.maps.SupportMapFragment" /> 

</RelativeLayout> 

的java文件

package in.wptrafficanalyzer.locationgooglemapv2demo; 

import android.app.Dialog; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.view.Menu; 
import android.widget.TextView; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 

public class MainActivity extends FragmentActivity implements LocationListener { 

    GoogleMap googleMap; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // Getting Google Play availability status 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); 

     // Showing status 
     if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available 

      int requestCode = 10; 
      Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
      dialog.show(); 

     }else { // Google Play Services are available 

      // Getting reference to the SupportMapFragment of activity_main.xml 
      SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

      // Getting GoogleMap object from the fragment 
      googleMap = fm.getMap(); 

      // Enabling MyLocation Layer of Google Map 
      googleMap.setMyLocationEnabled(true); 

      // Getting LocationManager object from System Service LOCATION_SERVICE 
      LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

      // Creating a criteria object to retrieve provider 
      Criteria criteria = new Criteria(); 

      // Getting the name of the best provider 
      String provider = locationManager.getBestProvider(criteria, true); 

      // Getting Current Location 
      Location location = locationManager.getLastKnownLocation(provider); 

      if(location!=null){ 
       onLocationChanged(location); 
      } 
      locationManager.requestLocationUpdates(provider, 20000, 0, this); 
     } 
    } 
    @Override 
    public void onLocationChanged(Location location) { 

     TextView tvLocation = (TextView) findViewById(R.id.tv_location); 

     // Getting latitude of the current location 
     double latitude = location.getLatitude(); 

     // Getting longitude of the current location 
     double longitude = location.getLongitude(); 

     // Creating a LatLng object for the current location 
     LatLng latLng = new LatLng(latitude, longitude); 

     // Showing the current location in Google Map 
     googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

     // Zoom in the Google Map 
     googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 

     // Setting latitude and longitude in the TextView tv_location 
     tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude); 

    } 

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

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

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

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
} 

回答

20

首先檢查文件here,它提供了良好的指示獲取用戶位置的最佳策略。

我個人通常開始與放置在一個位置標記在地圖retrivied與

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); 

,然後我開始監聽位置更新和移動標記。

它也取決於你的應用程序傾斜的位置有多準確,如果你不需要真正準確的位置,但面積足夠,也許你可以使用lastKnownLocation

你可以嘗試這樣的事情

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    // Getting Google Play availability status 
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); 

    // Showing status 
    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available 

     int requestCode = 10; 
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
     dialog.show(); 

    }else { // Google Play Services are available 

     // Getting reference to the SupportMapFragment of activity_main.xml 
     SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

     // Getting GoogleMap object from the fragment 
     googleMap = fm.getMap(); 

     // Enabling MyLocation Layer of Google Map 
     googleMap.setMyLocationEnabled(true); 

     // Getting LocationManager object from System Service LOCATION_SERVICE 
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

     // Creating a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 

     // Getting the name of the best provider 
     String provider = locationManager.getBestProvider(criteria, true); 

     // Getting Current Location 
     Location location = locationManager.getLastKnownLocation(provider); 

     LocationListener locationListener = new LocationListener() { 
      void onLocationChanged(Location location) { 
      // redraw the marker when get location update. 
      drawMarker(location); 
     } 

     if(location!=null){ 
      //PLACE THE INITIAL MARKER    
      drawMarker(location); 
     } 
     locationManager.requestLocationUpdates(provider, 20000, 0, locationListener); 
    } 
} 

private void drawMarker(Location location){ 
    // Remove any existing markers on the map 
    googleMap.clear(); 
    LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude()); 
    googleMap.addMarker(new MarkerOptions() 
    .position(currentPosition) 
    .snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()) 
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) 
    .title("ME")); 
} 

而且你不需要的活動類implements LocationListener,你可以定義一個監聽器並將其註冊爲我做了上述

附:我沒有一個編輯器的兒子我的代碼可以包含錯字

希望這有助於歡呼

+0

@ drChivas這正是我想做的事情,我需要與包含經緯度文字在地圖上顯示用戶的當前位置和長,但我不知道如何做到這一點 – user2277081

+0

@ user2277081我編輯了答案 – DrChivas

+2

+1'map.setMyLocationEnabled(true)' –

1

全面快捷的android系統中定義谷歌地圖Android版V2 ......

XML文件:

<fragment 
     android:id="@+id/map" 
     android:name="com.google.android.gms.maps.SupportMapFragment" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

Menifest文件:

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

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

<!-- Map permission Starts --> 
<permission 
    android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" 
    android:protectionLevel="signature" /> 

<uses-permission android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" /> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 

<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true" /> 

<!-- Map permission Starts --> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="com.example.mapdemoapiv2.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> 
    <activity android:name=".MapDetail" > 
    </activity> 

    <meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="Your Key" /> 

    <uses-library android:name="com.google.android.maps" /> 
</application> 

活動類:

public class MainActivity extends android.support.v4.app.FragmentActivity 
{ 
    GoogleMap googleMap; 
    MarkerOptions markerOptions; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    setUpMapIfNeeded(); 

    GetCurrentLocation(); 

    } 

private void setUpMapIfNeeded() { 
    if (googleMap == null) { 

     Log.e("", "Into null map"); 
     googleMap = ((SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map)).getMap(); 

     googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
       MainActivity.this)); 

     if (googleMap != null) { 
      Log.e("", "Into full map"); 
      googleMap.setMapType(googleMap.MAP_TYPE_NORMAL); 
      googleMap.getUiSettings().setZoomControlsEnabled(false); 
     } 
    } 
} 

private void GetCurrentLocation() { 

    double[] d = getlocation(); 
    Share.lat = d[0]; 
    Share.lng = d[1]; 

    googleMap 
      .addMarker(new MarkerOptions() 
        .position(new LatLng(Share.lat, Share.lng)) 
        .title("Current Location") 
        .icon(BitmapDescriptorFactory 
          .fromResource(R.drawable.dot_blue))); 

      googleMap 
       .animateCamera(CameraUpdateFactory.newLatLngZoom(
         new LatLng(Share.lat, Share.lng), 5)); 
} 

public double[] getlocation() { 
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    List<String> providers = lm.getProviders(true); 

    Location l = null; 
    for (int i = 0; i < providers.size(); i++) { 
     l = lm.getLastKnownLocation(providers.get(i)); 
     if (l != null) 
      break; 
    } 
    double[] gps = new double[2]; 

    if (l != null) { 
     gps[0] = l.getLatitude(); 
     gps[1] = l.getLongitude(); 
    } 
    return gps; 
} 
+0

我們可以通過Google Maps API獲取位置嗎?因爲有些設備沒有GPS。 –

0

容易這樣的:

在此之後 -

<meta-data 
    android:name="com.google.android.maps.v2.API_KEY" 
    android:value="Your Key" /> 

把這個 -

<meta-data android:name="com.google.android.gms.version" android:value="4030500" /> 
4

我有同樣的問題,並發現了一種使用谷歌地圖API來做到這一點:

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() { 
    @Override 
    public void onMyLocationChange(Location location) { 
     LatLng loc = new LatLng(location.getLatitude(), location.getLongitude()); 
     mMarker = mMap.addMarker(new MarkerOptions().position(loc)); 
     if(mMap != null){ 
      mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f)); 
     } 
    } 
}; 

,然後設置偵聽器map:

mMap.setOnMyLocationChangeListener(myLocationChangeListener); 

這將在地圖第一次找到位置時被調用。

根本不需要LocationServiceLocationManager

+0

這符合預期。謝謝。但我想修改它,以便能夠返回包含lat和lng的double []。這怎麼可能?這對我來說看起來很奇怪。 :/ –

1

這是更好地使用:

Location currentLocation = 
    LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

Documentation