2013-04-14 7 views
13

Я создаю приложение с видом карты google и хочу, чтобы это приложение обнаружило текущее местоположение пользователя и отобразило lat и long с маркером на карте, но все i может до сих пор отображать карту google и обнаружение текущего местоположения без какого-либо отображаемого маркера и без какого-либо текста, отображаемого на экране lat и longandroid + google map 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, вы можете просто определить слушателя и зарегистрировать его, как я сделал выше

P.S. У меня нет редактора сына моего код может содержать опечатка

Надеется, что это помогает, веселит

+0

@ drChivas, что это именно то, что я хочу сделать, мне нужно, чтобы отобразить текущее местоположение пользователя на карте с текстом, которые содержат лат и долго, но я не знал, как это сделать – user2277081

+0

@ user2277081 Я отредактировал ответ – DrChivas

+2

+1 для 'map.setMyLocationEnabled (true)' –

1

Полный ярлык для определения андроида v2 Google Map в андроиде ......

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

Можем ли мы найти местоположение через API Карт Google? потому что некоторые устройства не имеют 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 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)); 
     } 
    } 
}; 

, а затем установить слушателя для карта:

mMap.setOnMyLocationChangeListener(myLocationChangeListener); 

Это будет вызвано, когда карта сначала найдет местоположение.

Нет необходимости в LocationService или LocationManager.

+0

Работает так, как ожидалось. Благодарю. Но я хочу изменить его, чтобы иметь возможность возвращать double [], содержащий lat и lng. Как это возможно? Мне это кажется странным. : / –

1

Лучше использовать:

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

Documentation

Смежные вопросы