如何在用户当前位置添加标记并在标题中显示当前的本地名称?

时间:2016-11-04 08:30:08

标签: android google-maps marker

我想为当前的GPS位置跟踪器创建应用。现在我想要的是如何在用户当前位置添加标记,我还想将当前的本地名称显示为标题。我怎么能实现这个目标呢?

活动代码 -

public class MyActivity extends FragmentActivity implements LocationListener {

    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        setContentView(R.layout.activity_my);
        SupportMapFragment supportMapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
        googleMap = supportMapFragment.getMap();
        googleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        locationTv.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
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }
}

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=".MyActivity">

    <fragment
        android:id="@+id/googleMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_above="@+id/latlongLocation" />

    <TextView
        android:id="@+id/latlongLocation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"
        android:background="#ff058fff"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:textColor="#ffffffff"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" />
</RelativeLayout>

3 个答案:

答案 0 :(得分:0)

在onLocationChanged方法中添加以下代码:

mMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(geoPoint[0]), Double.valueOf(geoPoint[1]))).title("Place1").icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_icon)));

它可能对你有帮助。

对于完整的项目你可以参考以下链接: 完整项目可在github.com/josuadas/LocationDemo

中找到

答案 1 :(得分:0)

除了@kgsharathkumar answer您还可以使用以下代码获取当地名称:

private String getAddressOfLatLng() {
    String addressStr = "";
    List<Address> addresses = null;
    Geocoder geocoder = new Geocoder(this.getActivity(), Locale.US);
    try {
        addresses = geocoder.getFromLocation(mLastSeenMarker.getPosition().latitude,
                mLastSeenMarker.getPosition().longitude, 1);

        if (addresses != null & addresses.size() > 0) {
            Address address = addresses.get(0);
            for (int i = 0; i < address.getMaxAddressLineIndex() - 1; i++) {
                if (!TextUtils.isEmpty(address.getAddressLine(i))) {
                    addressStr += address.getAddressLine(i) + "\n";
                }
            }

            int lastIndex = address.getMaxAddressLineIndex() - 1;
            if (lastIndex >= 0 && lastIndex < address.getMaxAddressLineIndex()) {
                addressStr += address.getAddressLine(lastIndex);
            }

        } else {
            addressStr = getString(R.string.unknown);
        }

    } catch (IOException e) {
        addressStr = getString(R.string.unknown);
    }
    return addressStr;
}

并以这种方式使用它:

Marker marker = mGoogleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .title(getAddressOfLatLng(latitude, longitude))
                    .icon(<your_marker_icon>));

答案 2 :(得分:0)

Try this
                    markerOptions = new MarkerOptions();
                    userCurrentLat = "Your latitude";
                    userCurrentLong = "Your longitude";
                    googleMap.getUiSettings().setMapToolbarEnabled(false);
                    googleMap.setMyLocationEnabled(true);
                    Geocoder geo = new Geocoder(ActivityMapFullScreenView.this);
                    List<Address> addresses = null;
                    addresses = geo.getFromLocation(Double.parseDouble(userCurrentLat), Double.parseDouble(userCurrentLong), 1);
                    if (addresses.isEmpty()) {
                        Toast.makeText(context, "Waiting for Location", Toast.LENGTH_SHORT).show();
                    }
                    if (addresses.size() > 0) {
                        if (addresses.get(0).getAddressLine(3) == null) {
                            currentAddress = addresses.get(0).getAddressLine(0) + " " + addresses.get(0).getAddressLine(1) + " " + addresses.get(0).getAddressLine(2);
                        } else if (addresses.get(0).getAddressLine(2) == null) {
                            currentAddress = addresses.get(0).getAddressLine(0) + " " + addresses.get(0).getAddressLine(1);
                        } else {
                            currentAddress = addresses.get(0).getAddressLine(0) + " " + addresses.get(0).getAddressLine(1) + " " + addresses.get(0).getAddressLine(2).replace("null", "") + " " + addresses.get(0).getAddressLine(3);
                        }
                        // yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
                        //String address = addresses.get(0).getSubLocality();
                    }
                    currentAddress.replace("null", "");
                    LatLng latLng = new LatLng(Double.parseDouble(userCurrentLat), Double.parseDouble(userCurrentLong));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
                    markerOptions.position(latLng);

                    googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(ActivityMapFullScreenView.this));
                    googleMap.addMarker(markerOptions.title(getResources().getString(R.string.share_this_loc)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_green_pin))).showInfoWindow();
    enter code here