2013-04-14 13 views
13
Tworzę aplikację z widokiem mapy google i chcę, aby ta aplikacja wykryła bieżącą lokalizację użytkownika i wyświetlała szerokość i długość z markerem na mapie, ale wszystko ja może zrobić do tej pory wyświetlanie mapy google i wykrywanie bieżącej lokalizacji bez wyświetlania jakiegokolwiek znacznika i bez żadnego tekstu pojawia się długi i długi

Nie dodałem do tej pory znacznika, ponieważ nie wiem gdzie umieścić go w kodzie i jaka jest najlepsza praktyka, aby to zrobić ktoś może mi pomóc ???????????? to jest kod:android + mapa google api v2 + aktualna lokalizacja

plik manifestu

<?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> 

plik 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> 

plik 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; 
    } 
} 

Odpowiedz

20

Najpierw sprawdź dokumentację here, to daje dobre wskazanie na najlepsze strategie uzyskiwania pozycji użytkownika.

Osobiście zwykle zaczynają mapa z markera umieszczonego na pozycji retrivied z

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); 

a potem zacząć słuchać do aktualizacji pozycji i przesunąć znacznik.

Zależy również od tego, jak dokładna pozycja jest potrzebna do celu danej aplikacji, jeśli nie potrzebujesz naprawdę dokładnej pozycji, ale obszar jest wystarczający, możesz po prostu użyć lastKnownLocation.

Można spróbować coś takiego

@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")); 
} 

Również nie trzeba klasę aktywny do implements LocationListener, można po prostu zdefiniować słuchacza i zarejestrować go jak ja powyżej

PS: Ja nie mam syna edytor mój kod może zawierać literówki

Nadzieja to pomaga, okrzyki

+0

@ drChivas to jest dokładnie to, co chcę zrobić i trzeba wyświetlić bieżącą lokalizację użytkownika na mapie z tekstem, które zawierają lat i długo, ale nie wiedziałem, jak to zrobić – user2277081

+0

@ user2277081 Edytowałem odpowiedź – DrChivas

+2

+1 dla 'map.setMyLocationEnabled (true)' –

1

Pełna skrót do definiowania map Google android android v2 w ......

XML File:

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

Menifest file:

<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> 

Klasa aktywności:

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

Czy możemy uzyskać lokalizację za pomocą Google Maps API? ponieważ niektóre urządzenia nie mają GPS. –

0

łatwo tak:

po tym -

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

umieścić to -

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

prostu miałem ten sam problem i znaleźć sposób, aby to zrobić za pomocą interfejsu API Google Maps:

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)); 
     } 
    } 
}; 

a następnie ustawić słuchacza dla mapa:

mMap.setOnMyLocationChangeListener(myLocationChangeListener); 

Zostanie on wywołany, gdy mapa znajdzie pierwszą lokalizację.

Nie ma potrzeby, aby LocationService lub LocationManager w ogóle.

+0

To działa zgodnie z oczekiwaniami. Dzięki. Ale chcę go zmodyfikować, aby móc zwrócić double [] zawierający lat i lng. Jak to możliwe? Wydaje mi się to dziwne. : / –

1

Lepiej jest użyć:

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

Documentation

Powiązane problemy