简体   繁体   English

Android | Google地图获取当前位置和更新

[英]Android | Google Maps Getting Current Location and Update

I am trying to get my current location on map and update it when I move. 我想在地图上获取当前位置并在移动时更新它。 Every time when an update happens, I want to get current longtidude and latitute values to use in other methods. 每当更新发生时,我想获得当前的longtidude和latitute值以用于其他方法。

private LocationRequest request = LocationRequest.create().setInterval(50000);

I think I have to use LocationRequest . 我想我必须使用LocationRequest I created an object which will update its location every 5 minutes. 我创建了一个每5分钟更新一次位置的对象。 But now I don't have any idea how to use it. 但现在我不知道如何使用它。 I checked tutorials on internet but they are so complicated for a beginner. 我在互联网上查了教程,但对于初学者来说它们是如此复杂。 Does anybody have simple solution? 有人有简单的解决方案吗?

EDIT 编辑

This is how my code looks now : 这就是我的代码现在的样子:

public class MainActivity extends Activity implements LocationListener {

private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;

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

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);


    getLocation();
    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

}

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


@Override
public void onLocationChanged(Location location) {

    if (location != null) {

        longitude = location.getLongitude();

        latitude = location.getLatitude();


        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }

}

public void getLocation()
{

    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

}

} }

When I tried to test it, my app stopped working. 当我尝试测试时,我的应用程序停止了工作。 Since this is my first android app and I am not very good at it, I couldn't find whats wrong. 由于这是我的第一个Android应用程序,我不是很擅长,我找不到什么错。

for location use this 对于位置使用这个

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Define a listener that responds to location updates

locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {

                // Called when a new location is found by the network location provider.

                longitude = String.valueOf(location.getLongitude());

                latitude = String.valueOf(location.getLatitude());

                Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        public void onProviderEnabled(String provider) {

        }

        public void onProviderDisabled(String provider) {

        }

};

// getting GPS status

isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// check if GPS enabled

if (isGPSEnabled) {

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {

                longitude = String.valueOf(location.getLongitude());

                latitude = String.valueOf(location.getLatitude());

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        } else {

                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                if (location != null) {

                        longitude = String.valueOf(location.getLongitude());

                        latitude = String.valueOf(location.getLatitude());

                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                } else {

                        longitude = "0.00";

                        latitude = "0.00";

                }

        }

}

from http://androidadvance.com/android_snippets.php#h.r43fot3suy6h 来自http://androidadvance.com/android_snippets.php#h.r43fot3suy6h

use gps to determine location ( longtidude and latitute values ) and pass it to maps 使用gps确定位置(longtidude和latitute值)并将其传递给地图

this mainactivity.java for gps 

public class GpsBasicsAndroidExample extends Activity implements LocationListener {

private LocationManager locationManager;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps_basics_android_example);
    text=(TextView)findViewById(R.id.tv1);

    /********** get Gps location service LocationManager object ***********/
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    /*
      Parameters :
         First(provider)    :  the name of the provider with which to register 
         Second(minTime)    :  the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value. 
         Third(minDistance) :  the minimum distance interval for notifications, in meters 
         Fourth(listener)   :  a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update 
    */

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);

    /********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}

/************* Called after each 3 sec **********/
@Override
public void onLocationChanged(Location location) {

    String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
    //Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    text.setText(str);
}

@Override
public void onProviderDisabled(String provider) {

    /******** Called when User off Gps *********/

    Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}

@Override
public void onProviderEnabled(String provider) {

    /******** Called when User on Gps  *********/

    Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}

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

}

} }

and this for maps 这对于地图

main.java

enter code here

public class MainActivity extends FragmentActivity { 公共类MainActivity扩展FragmentActivity {

GoogleMap mMap;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
    Marker ciu = mMap.addMarker(new MarkerOptions()
                              .position(CIU).title("My Office"));


    final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
    Marker ciu1 = mMap.addMarker(new MarkerOptions()
                              .position(CIU1).title("My Second Office"));

    final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
    Marker ciu2 = mMap.addMarker(new MarkerOptions()
                              .position(CIU2).title("My thired Office"));



}

} }

Here is how you can do. 这是你可以做的。 I will try to make it simple for you: 我会尽量让你变得简单:

  • Add LocationListener interface to your extended activity class using implements keyword. 使用implements关键字将LocationListener接口添加到扩展活动类。 This will force you to Override some methods you will need to find your current location. 这将强制您覆盖查找当前位置所需的一些方法。

     public class A extends Activity implements LocationListener {} 
  • Create an instance of the Location Manager class which would act as a hook to call various services and methods in Location package. 创建一个Location Manager类的实例,它将作为一个钩子来调用Location包中的各种服务和方法。

     private LocationManager locationManager; 
  • Create a method like getLocation() and call the predefined service method from the Location Manger instance. 创建一个类似getLocation()的方法,并从Location Manger实例调用预定义的服务方法。

     locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); 
  • In the onLocationChanged() method you can request the latitude using getLatitude() and longitude using getLongitude() using these two methods that are the part of Location Manager class. 在onLocationChanged()方法中,您可以使用getLongitude()使用getLongitude()使用这两个方法(位置管理器类的一部分)请求纬度。

  • Store the two values obtained by these methods in two separate variables make sure they are of Double type, later you can convert them in String type and then display them on a Text view of your app activity. 将这些方法获得的两个值存储在两个单独的变量中,确保它们是Double类型,稍后您可以将它们转换为String类型,然后在应用程序活动的Text视图中显示它们。

     if (location != null) { longitude = String.valueOf(location.getLongitude()); latitude = String.valueOf(location.getLatitude()); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } 
  • Call the getLocation() method in your onCreate() and display them on app screen by having a TextView or a toast. 调用onCreate()中的getLocation()方法,并通过TextView或Toast在应用程序屏幕上显示它们。

     Toast.makeText(getApplicationContext(), "Your Location is - \\nLat: " + latitude + "\\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
  • Last but not the least dont forget to add permissions in you Manifest file. 最后但并非最不要忘记在Manifest文件中添加权限。

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

Fore more details please refer to this link . 更多详情请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM