基于坐标显示在android中的MAP上的位置

时间:2015-06-16 04:04:00

标签: android google-maps

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

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

这是我的代码(Not Full)

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网站推荐给我当前的应用

此致

3 个答案:

答案 0 :(得分:0)

创建地图活动并通过捆绑包传递位置或将其保存在共享偏好

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

答案 1 :(得分:0)

您需要将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

答案 2 :(得分:0)

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

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

首先,确保现有活动中的当前位置具有双倍值:

//instance variables:
double lat;
double lon;

onLocationChanged()回调中设置lat / lon:

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

在现有活动的布局中创建一个按钮,在点击监听器中,您将创建一个LatLng对象,并将其在Intent中发送到地图活动:

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

然后,在您的地图活动中,您将从Bundle中获取LatLng中的onCreate()对象:

    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地图,并在build.gradle文件中包含Google Play服务(使用您使用的版本更新版本):

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