Friday, July 29, 2011

Get the the coordinates (Latitude and Longitude) currently displayed on MapView

Here is a example to get the coordinates (Latitude and Longitude) currently displayed on MapView.

Get the the coordinates (Latitude and Longitude) currently displayed on MapView

To get the coordinate of a point corspondint to a pixel on screen, we can use the method MapView.getProjection().fromPixels(x, y).

package com.exercise.AndroidMap;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidMapActivity extends MapActivity {

MapView myMap;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMap = (MapView) findViewById(R.id.map);
myMap.setBuiltInZoomControls(true);

Button buttonGetInfo = (Button)findViewById(R.id.getinfo);
buttonGetInfo.setOnClickListener(buttonGetInfoOnClickListener);
}

@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}

Button.OnClickListener buttonGetInfoOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

GeoPoint mapCenter = myMap.getMapCenter();

float centerLatitude = (float)(mapCenter.getLatitudeE6())/1000000;
float centerLongitude = (float)(mapCenter.getLongitudeE6())/1000000;

float latitudeSpan = (float)(myMap.getLatitudeSpan())/1000000;
float longitudeSpan = (float)(myMap.getLongitudeSpan()/1000000);

GeoPoint mapTopLeft = myMap.getProjection().fromPixels(0, 0);
float topLatitude = (float)(mapTopLeft.getLatitudeE6())/1000000;
float leftLongitude = (float)(mapTopLeft.getLongitudeE6())/1000000;

GeoPoint mapBottomRight
= myMap.getProjection().fromPixels(myMap.getWidth(), myMap.getHeight());
float bottomLatitude = (float)(mapBottomRight.getLatitudeE6())/1000000;
float rightLongitude = (float)(mapBottomRight.getLongitudeE6())/1000000;

int zoomLevel = myMap.getZoomLevel();

String info =
"Center: " + centerLatitude + "/" + centerLongitude + "\n"
+ "Top Left: " + topLatitude + "/" + leftLongitude + "\n"
+ "Bottom Right: " + bottomLatitude + "/" + rightLongitude + "\n"
+ "latitudeSpan: " + latitudeSpan + "\n"
+ "longitudeSpan: " + longitudeSpan + "\n"
+ "zoomLevel: " + zoomLevel;

Toast.makeText(AndroidMapActivity.this,
info,
Toast.LENGTH_LONG).show();
}};
}


Related Article:
- A minimal Map application using MapActivity

next:
- Draw on a custom View over MapView

No comments: