我正在开发一个包含3个活动的android应用程序,其中一个是map。我正在使用谷歌地图
我想要的是什么:
当用户打开活动(地图)时,它会向用户显示她的位置而不是坐标。
用户还应该能够使用别针对任何地方进行定位(压缩),我的应用必须将此引脚的坐标存储在变量中,以便我以后可以使用它。
public class LActivity extends MapActivity
{
/** Called when the activity is first created. */
MapView mapView;
GeoPoint geo;
MapController mapController;
LocationManager locationManager;
CustomPinpoint itemizedoverlay;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
// create a map view
//LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);
mapView.setBuiltInZoomControls(true);
// Either satellite or 2d
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
public class GeoUpdateHandler implements LocationListener {
@Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
这是CustomPinpoint类
public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {
static int maxNum = 3;
OverlayItem overlays[] = new OverlayItem[maxNum];
int index = 0;
boolean full = false;
CustomPinpoint itemizedoverlay;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
@Override
protected OverlayItem createItem(int i) {
return overlays[i];
}
@Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}
}
public void addOverlay(OverlayItem overlay) {
if (index < maxNum) {
overlays[index] = overlay;
} else {
index = 0;
full = true;
overlays[index] = overlay;
}
index++;
populate();
}
}
答案 0 :(得分:1)
我已经实现了你想要的相同的东西。我正在为您提供示例代码。在这里,我还在获取位置时实现了ProgressDialog。
这是获取位置的起点。我将此命名为AndroidLocationActivity。这是您的应用启动时开始的第一项活动。
String provider;
public double latitude, longitude = 0;
CurrentPositionTask getCurrentLocation;
Location currentLocation;
LocationListener locationListener;
LocationManager locationManager;
private long time=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setCriteria();
currentLocation = AndroidLocationActivity.this.locationManager.getLastKnownLocation(provider);
if (currentLocation == null) {
currentLocation = new Location(provider);
}
time = currentLocation.getTime();
if (latitude == 0 && longitude == 0) {
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
Toast.makeText(AndroidLocationActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();
此处设置时间不超过1分钟的时间,而不是我更新位置。
if (time >= 100000) {
latitude = 0;
longitude = 0;
}
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null");
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
runAsyncTask();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
locationManager.removeUpdates(locationListener);
}
public void setCriteria() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
provider = locationManager.getBestProvider(criteria, true);
Toast.makeText(getApplicationContext(), "Provider - " + provider, Toast.LENGTH_SHORT).show();
if (provider == null) {
provider = LocationManager.GPS_PROVIDER;
}
}
public void runAsyncTask() {
// TODO Auto-generated method stub
if (getCurrentLocation == null) {
getCurrentLocation = new CurrentPositionTask();
}
if (getCurrentLocation != null) {
getCurrentLocation.execute("Searching for Location");
}
}
public boolean checkConnection()
{
//ARE WE CONNECTED TO THE NET
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (AndroidLocationActivity.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
private class CurrentPositionTask extends AsyncTask<String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(AndroidLocationActivity.this);
private boolean flag = true;
public CurrentPositionTask() {
locationListener = new MyLocationListener();
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
try {
if (checkConnection()) {
Dialog.setTitle("Loading");
Dialog.setMessage("Searching for Location");
Dialog.show();
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}
else {
Toast.makeText(getApplicationContext(), "Internet is Not Available", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
while (flag) {
if (latitude !=0 && longitude != 0) {
flag=false;
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidLocationActivity.this, "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
if (Dialog != null && Dialog.isShowing()) {
Dialog.dismiss();
time=0;
Intent homeIntent = new Intent(AndroidLocationActivity.this.getApplicationContext(), HomeMenuActivity.class);
设置lat&amp;在这里开始新的活动
homeIntent.putExtra("lat", latitude);
homeIntent.putExtra("lng", longitude);
startActivity(homeIntent);
}
locationManager.removeUpdates(locationListener);
}
}
class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
这是我显示地图的功能。这是HomeMenuActivity
public static Context context;
onCreate(..) {
context = getApplicationContext(); // it will be used in Itemized Overlay
latitude = getIntent().getDoubleExtra("lat", 0);//get the lat & lng
longitude = getIntent().getDoubleExtra("lng", 0);
}
public void showMap() {
// TODO Auto-generated method stub
try {
geoPoint = new GeoPoint((int)(latitude * 1E6),(int)(longitude * 1E6));
mapview = (MapView)findViewById(R.id.mapview);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapview.setTraffic(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(your pic....);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ItemizedOverlay Class
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
@Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
Toast.makeText(HomeMenuActivity.context, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
希望这会有所帮助.....
答案 1 :(得分:0)
删除onCreate上的方法并添加以下代码:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
initMap(); // This is the method which initialize the map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
@Override
public void onResume()
{
super.onResume();
try
{
initMyLocation();
}catch(Exception e){}
}
/**
* Inits the map.
*/
protected void initMap()
{
mapView = (MyMapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapView.setStreetView(false);
mapController = mapView.getController();
mapOverlay = new MapOverlay();
List<Overlay> overlays = mapView.getOverlays();
overlays.add(mapOverlay);
mapController.setZoom(14);
mapView.invalidate();
}
/**
* Initialises the MyLocationOverlay and adds it to the overlays of the map.
*/
public void initMyLocation() {
try
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location l = LocationService.getLastKnownLocation(lm);
int lat = (int)(l.getLatitude()*1E6);
int lng = (int)(l.getLongitude()*1E6);
mapController.setCenter(new GeoPoint(lat , lng));
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(myLocOverlay);
mapController.setCenter(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
findMe();
}
/**
* This method will animate to my current position
*/
public void findMe()
{
try
{
mapController.animateTo(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
}
然后,要存储叠加层以供将来使用,您可以使用SharedPreferences或SQLite。每个教程都有很多教程。