【问题标题】:Based On Co-ordinates show location on MAP in android基于坐标在android中的MAP上显示位置
【发布时间】:2015-06-16 04:04:00
【问题描述】:

我制作了一个应用程序,它使用 GPS 服务为您提供当前的纬度和经度。 现在我计划根据这个坐标在 MAP 上显示位置

我想创建 2 个活动。第一个已经创建,我在 TextView 中显示纬度和经度。在第二个活动中,我想显示将显示位置的地图。要从一项活动转到另一项活动,我将在第一项活动中使用一个按钮。

这是我的代码(不完整)

protected LocationManager locMan;
protected LocationListener locLis;
protected Context contex;
TextView txtview;
String lat,provider;
protected String latitude,longtitude;
protected boolean gps_enable,network_enable;


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

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F44336")));

    txtview = (TextView)findViewById(R.id.locView);

    locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

}

@Override
public void onLocationChanged(Location loc){

     txtview = (TextView)findViewById(R.id.locView);
     txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude());
}

注意 :- 我已经为我当前的应用程序参考了 javapapers 网站

问候

【问题讨论】:

  • 兄弟,他已经在 MAP 上显示并且在标记时遇到问题,但我的问题是差异。我有坐标,我想根据我得到的坐标在 MAP 上显示。

标签: android google-maps


【解决方案1】:

创建 Map Activity 并通过 bundle 传递位置或将其保存在 sharedpreference 中

public class MapActivity extends ActionBarActivity{

private GoogleMap googleMap;
FragmentManager fm;
private Location mLocation;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fm = getSupportFragmentManager();

    // get location from bundle or sharedprefs
    // mLocation = ...

    try {
        if (googleMap == null) {
            googleMap = ((SupportMapFragment) fm.findFragmentById(R.id.map)).getMap();
            googleMap.getUiSettings().setZoomGesturesEnabled(true);
        }
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    } catch (Exception e) {
        e.printStackTrace();
    }
    MarkerOptions TP = new MarkerOptions().title("title").position(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker));
    googleMap.addMarker(TP);

}}    

这个活动的xml布局是

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

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

【讨论】:

    【解决方案2】:

    您需要在地图上使用MapViewMyLocationOverLay,因为Android 会为您显示用户的位置。

    map=(MapView)findViewById(R.id.whatever_your_mapview_id_is);
    map.getOverlays().add(new MyLocationOverlay(this, map));
    

    参考:display google maps using coordinates obtained using gps

    【讨论】:

    • 请注意,这段代码非常过时,使用 Google Maps API v2,您只需调用map.setMyLocationEnabled(true);
    【解决方案3】:

    您可以使用LatLng 对象将位置传递给地图活动,因为它是可打包的,请参阅this answer

    然后,您可以在 MapsActivity 中创建一个 Marker,并使用 CameraPosition 类将地图视图移动到指定位置。

    首先,确保您在现有 Activity 中的当前位置具有双精度值:

    //instance variables:
    double lat;
    double lon;
    

    onLocationChanged() 回调中设置纬度/经度:

    @Override
    public void onLocationChanged(Location loc){
    
         lat = loc.getLatitude(); //added
         lon = loc.getLongitude(); //added
    
         txtview = (TextView)findViewById(R.id.locView);
         txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude());
    }
    

    在现有 Activity 的布局中创建一个 Button,然后在点击侦听器中创建一个 LatLng 对象并将其在 Intent 中发送到 Maps Activity:

        Button b = (Button) findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LatLng fromPostion = new LatLng(lat, lon );
    
                Bundle args = new Bundle();
                args.putParcelable("location", fromPostion);
    
                Intent i = new Intent(this, MapsActivity.class);
                i.putExtras(args);
                startActivity(i);
            }
        });
    

    然后,在您的 Maps Activity 中,您将从 Bundle 中获取 onCreate() 中的 LatLng 对象:

        LatLng latlng;  //Create as instance variable
    

    onCreate():

        Bundle b = getIntent().getExtras();
        if (b != null){
            latlng = (LatLng) b.getParcelable("location");
        }
    

    然后,在该位置添加标记并设置相机位置和缩放:

    private void setUpMap() {
    
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setMyLocationEnabled(true);
    
    
        MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location");
    
        // Changing marker icon
        marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    
        Marker m = mMap.addMarker(marker);
    
        //move camera position and zoom to specified location
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latlng).zoom(8).build();
    
        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    
    }
    

    您的完整地图活动可能如下所示:

    public class MapsActivity extends ActionBarActivity implements
            GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback {
    
        private GoogleMap mMap;
        LatLng latlng;
        LocationRequest mLocationRequest;
        GoogleApiClient mGoogleApiClient;
        LocationManager manager;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_maps);
    
            Bundle b = getIntent().getExtras();
            if (b != null){
                latlng = b.getParcelable("location");
            }
    
            manager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
    
            setUpMapIfNeeded();
    
            buildGoogleApiClient();
            mGoogleApiClient.connect();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            setUpMapIfNeeded();
    
    
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                    !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                AlertDialog.Builder builder = new AlertDialog.Builder(this)
                        .setTitle("Location is disabled")
                        .setMessage("Please enable your location")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100);
                            }
                        });
    
                AlertDialog dialog = builder.create();
                dialog.show();
    
            } else {
                Log.v("Connection Status", String.valueOf(mGoogleApiClient.isConnected()));
                mGoogleApiClient.connect();
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK && requestCode == 100) {
                Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show();
                if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                        manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    
                    Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show();
                    //At least one provider enabled, connect GoogleApiClient
                    mGoogleApiClient.connect();
    
                }
            }
        }
    
        @Override
        protected void onPause(){
            super.onPause();
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }
        }
    
    
        protected synchronized void buildGoogleApiClient() {
            Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    
        @Override
        public void onConnected(Bundle bundle) {
            Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
    
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(10);
            mLocationRequest.setFastestInterval(10);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            mLocationRequest.setSmallestDisplacement(0.1F);
    
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    
    
        private void setUpMapIfNeeded() {
            // Do a null check to confirm that we have not already instantiated the map.
            if (mMap == null) {
                // Try to obtain the map from the SupportMapFragment.
                mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                        .getMap();
    
                // Check if we were successful in obtaining the map.
                if (mMap != null) {
                    setUpMap();
                }
    
            }
        }
    
        private void setUpMap() {
    
            mMap.getUiSettings().setMapToolbarEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.setMyLocationEnabled(true);
    
    
            MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location");
    
            // Changing marker icon
            marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    
            Marker m = mMap.addMarker(marker);
    
            //move camera position and zoom to specified location
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latlng).zoom(8).build();
    
            mMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));
    
    
        }
    
    
        @Override
        public void onConnectionSuspended(int i) {
            Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onLocationChanged(Location location) {
    
            Log.d("locationtesting",  "lat: " + location.getLatitude() + " lon: " + location.getLongitude());
    
        }
    
    }
    

    MapsActivity 的布局 xml:

    <fragment 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" android:id="@+id/map" tools:context=".MapsActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment" />
    

    请注意,您还需要在 Google Developer Console 中启用 Google Maps,并将 Google Play Services 包含在您的 build.gradle 文件中(使用您正在使用的版本更新版本):

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.1.1'
        compile 'com.google.android.gms:play-services:7.3.0'
    }
    

    最后一件事是为 Google Maps API v2 设置您的 AndroidManifest.xml:

    权限:

     <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
        <!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
             Google Maps Android API v2, but are recommended.
        -->
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    元数据标签,确保它们在应用标签内:

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="Your-API-Key" />
    

    【讨论】:

    • 兄弟,我已经显示了 progressDialog 微调器,但我只想要它获取位置。如果找到坐标,它应该停止显示。
    • @user3384581 只需关闭 onLocationChanged() 中的对话框。此外,如果您只需要一次位置更新,请务必在此时取消注册回调。
    • 谢谢老兄......我会照你说的做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2015-07-04
    • 1970-01-01
    • 2015-10-28
    • 2015-03-07
    • 2019-10-19
    相关资源
    最近更新 更多