【问题标题】:How to add marker on user current position and show current local place name in title?如何在用户当前位置添加标记并在标题中显示当前本地地名?
【发布时间】:2016-11-04 08:30:07
【问题描述】:

我想为当前的 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>

【问题讨论】:

标签: android google-maps marker


【解决方案1】:

除了@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】:

    在您的 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

    【讨论】:

    • 什么也没发生。在当前位置仍然只显示蓝色图标。
    • 现在检查我添加了完整项目的链接它对你有帮助......当然
    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      相关资源
      最近更新 更多