基于坐标在android地图上显示位置
我已经做了一个应用程序,它使用GPS服务为您提供当前的纬度和经度。 现在我计划根据这个坐标在地图上显示位置 我想创建两个活动。第一个已经创建,我在TextView中显示纬度和经度。在第二个活动中,我想显示显示位置的地图。要从一个活动转到另一个活动,我将在第一个活动中使用按钮 这是我的代码(不完整) 注意:-我已经参考了javapapers网站了解我当前的应用程序基于坐标在android地图上显示位置,android,google-maps,Android,Google Maps,我已经做了一个应用程序,它使用GPS服务为您提供当前的纬度和经度。 现在我计划根据这个坐标在地图上显示位置 我想创建两个活动。第一个已经创建,我在TextView中显示纬度和经度。在第二个活动中,我想显示显示位置的地图。要从一个活动转到另一个活动,我将在第一个活动中使用按钮 这是我的代码(不完整) 注意:-我已经参考了javapapers网站了解我当前的应用程序 关于创建地图活动并通过bundle传递位置或将其保存在SharedReference中 public class MapActivit
关于创建地图活动并通过bundle传递位置或将其保存在SharedReference中
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"/>
您需要使用
MapView
和MyLocationOverLay
来显示地图,因为Android将为您显示用户的位置
map=(MapView)findViewById(R.id.whatever_your_mapview_id_is);
map.getOverlays().add(new MyLocationOverlay(this, map));
请参阅:您可以使用
LatLng
对象将位置传递给“地图”活动,因为它是可包裹的,请参阅
然后,您可以在MapsActivity中创建一个标记,并使用CameraPosition类将地图视图移动到指定位置
首先,确保现有活动中的当前位置具有双重值:
//instance variables:
double lat;
double lon;
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);
}
});
在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
对象,并将其发送到地图活动的意图中:
//instance variables:
double lat;
double lon;
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);
}
});
然后,在“地图”活动中,您将从捆绑包中获得onCreate()
中的LatLng
对象:
LatLng latlng; //Create as instance variable
在onCreate()
中:
然后,在该位置添加标记,并设置相机位置和缩放:
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:
//instance variables:
double lat;
double lon;
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);
}
});
<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 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" />
brother he已经在地图上显示了,在标记上有问题,但我的问题是不同的。我有坐标,我想根据我得到的坐标在地图上显示。请注意,此代码非常过时,使用Google Maps API v2,只需调用MAP.setMyLocationEnabled(true)代码>兄弟我已经显示了progressDialog微调器,但我只希望它获取位置。如果找到坐标,它应该停止显示。@user3384581只需关闭onLocationChanged()中的对话框即可。另外,如果您只需要一次位置更新,请确保在该点取消注册回调。谢谢,伙计。。我会照你说的去做