I am trying to buid a simple app that when user enter his desired location its map appear.But i am getting an error Cannot instantiate the type GeoPoint i have also installed Google Play Services.
here is the code :
public class MainActivity extends MapActivity {
EditText location;
Geocoder geoCoder;
GeoPoint p;
MapController controller;
MapView mapView;
Button btnSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location=(EditText)findViewById(R.id.txtAddress);
mapView = (MapView) findViewById(R.id.mapView);
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
List<Address> addresses;
try {
addresses = geoCoder.getFromLocationName(location.getText().toString(),1);
if(addresses.size() > 0)
{
p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
location.setText("");
}
else
{
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Google Map");
adb.setMessage("Please Provide the Proper Place");
adb.setPositiveButton("Close",null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Is there a particular reason you need to use v1 of the Google maps api, instead of the current v2? If not, try using LatLng to store the location, and map.moveCamera(LatLng, float zoom) to go to the desired location as shown here.
Related
I am a beginner of Android Developer. I am developing the Map Application. I have a function of searching address but I do not know how to search address by name using Google Map API V.2. Please suggest me the solution and some code to solve this. Thank you very much and Sorry with my English.
adderess = c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
// get address in string for used location for the map
/* get latitude and longitude from the adderress */
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocationName(adderess, 5);
if (addresses.size() > 0)
{
Double lat = (double) (addresses.get(0).getLatitude());
Double lon = (double) (addresses.get(0).getLongitude());
Log.d("lat-long", "" + lat + "......." + lon);
final LatLng user = new LatLng(lat, lon);
/*used marker for show the location */
Marker hamburg = map.addMarker(new MarkerOptions()
.position(user)
.title(adderess)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(user, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
}
catch (IOException e)
{
e.printStackTrace();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_map);
editText = (EditText) findViewById(R.id.editText1);
mapView = (MapView) findViewById(R.id.mapView);
btngo = (Button) findViewById(R.id.btnmapsites);
btngo.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
List<Address> addresses;
try{
addresses = geoCoder.getFromLocationName(editText.getText().toString(),1);
if(addresses.size() > 0){
p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
editText.setText("");
}else{
AlertDialog.Builder adb = new AlertDialog.Builder(SearchMapActivity.this);
adb.setTitle("Google Map");
adb.setMessage("Please Provide the Proper Place");
adb.setPositiveButton("Close",null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
One part of the application I am making requires google map. I want the user to be able to type into edittext some search string and then press a search button and the map will animate to the first result.
When I press the button the application searches and takes the first result and puts it into a geopoint, so that part of the program is working. But when I try to animate to that point the application crashes.
Here is the onCreate function where I successfully navigate to the location "Dalvík, Iceland".
public class LocationPicker extends MapActivity {
static GeoPoint point;
static MapController mc;
static MapView mapView;
private EditText location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_picker);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
location = (EditText)findViewById(R.id.locationString);
mc = mapView.getController();
String tmp = "Dalvík, Iceland";
try {
point = searchLocation(tmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mc.animateTo(point);
mc.setZoom(14);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
And my code for the button click is, and to be clear the System.out.println(point) prints valid point. But still when I click the button my application crashes.
public void search(View v) throws IOException{
GeoPoint tmpPoint = searchLocation(location.getText().toString());
System.out.println(tmpPoint);
if( tmpPoint != null){
mc.animateTo(tmpPoint);
mapView.invalidate();
}
}
And the searchLocation functions is as follows:
public GeoPoint searchLocation (String searchString) throws IOException{
Geocoder geo = new Geocoder(this);
List<Address> addr;
addr = geo.getFromLocationName(searchString, 10);
if(!addr.isEmpty()){
Address loc = addr.get(0);
GeoPoint point = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
return point;
}
else {
return null;
}
}
So to summerize I am clearly doing something wrong in the onclick "search" function.
Any ideas what is wrong?
You are not checking the right variable for null value:
if( point != null){
mc.animateTo(tmpPoint);
mapView.invalidate();
}
should be
if( tmpPoint!= null){
mc.animateTo(tmpPoint);
mapView.invalidate();
}
Additionnally, you want to make the call to the geoCoder.getFromLocationName method outside the UI thread as this can be time consumming. Use an AsyncTask for that for instance.
Finally, even if you get a list of addresses, they are not guaranted to have latitude and longitude. Use the hasLatitude and hasLongitude functions to pick the first address of the result list with coordinates.
I found the answer.
The problem causing this was this line
mapView.invalidate();
I wanna find the location on Map when using a virtual device (Emulator Android) because i have not a actual device.
Thanks for watching!
Here is my code :
enter code herepublic class GoogleMapExample3Activity extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
TextView txtView;
LinearLayout zoomControl;
GeoPoint geoPoint;
MapController mapController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView=(MapView) findViewById(R.id.mapView);
zoomControl=(LinearLayout) findViewById(R.id.zoomControl);
View view= mapView.getZoomControls();
zoomControl.addView(view,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mapView.setSatellite(true);
String address="New York";
Geocoder geoCoder=new Geocoder(this);
List<Address> list;
try {
list = geoCoder.getFromLocationName(address, 1);
Address a=list.get(0);
Double latitude=a.getLatitude();
Double longitude=a.getLongitude();
geoPoint=new GeoPoint( (int)(latitude*1E6),(int)(longitude*1E6));
mapController=mapView.getController();
mapController.animateTo(geoPoint);
mapController.setZoom(18);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
MapController mapController=mapView.getController();
switch (keyCode) {
case KeyEvent.KEYCODE_I:
mapController.zoomIn();
break;
case KeyEvent.KEYCODE_O:
mapController.zoomOut();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
I tryed but can't get a location from a address which was entered by user!
I need you help!
How to find a location on Map from a address which was be input by user?
Using Android Geocoder class,
Geocoder geoCoder = new Geocoder(this);
List<Address> listAddress;
GeoPoint geoPoint;
try {
listAddress = geoCoder.getFromLocationName(userAddress,1);
if (listAddress == null) {
return null;
}
Address location = listAddress.get(0);
geoPoint = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
Hope this will help you
http://eagle.phys.utk.edu/guidry/android/mappingDemo.html
I have this textbox in the other activity and a button which leads to this map. What i want to do is that it allows the user to click the map and pin point the location they wants, and they can also fetch that location's address back to the textbox without typing. Can it be done so? Since now there is this alert dialog box which pop up after user pin point it with 2 buttons(Yes and No) So if yes, fetch that location address back to the textbox. Any idea?
static EditText txtLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
MapOverlay mapOverlay = new MapOverlay();
mapOverlays.add(mapOverlay);
// obtain gps location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}
p = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
mc.animateTo(p);
mc.setZoom(18);
// Add a location marker
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listofOverlays = mapView.getOverlays();
listofOverlays.clear();
listofOverlays.add(mapOverlay);
// invalidate() method forces the MapView to be redrawn
mapView.invalidate();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean onTap(final GeoPoint p, MapView mapView) {
// TODO Auto-generated method stub
k = p;
mc = mapView.getController();
mc.animateTo(p);
mapView.invalidate();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
// txtLocation.setText(add);
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Change location..")
.setMessage("go to the new location?")
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
txtLocation.setText(add);
// Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
}
}).show();
return true;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
if (k != null) {
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(k, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x - 10, screenPts.y - 34, null);
}
return true;
}
}
}
Well you can try reverse geocoding. What that needs is you to supply the lat long of the point that the user tapped on, which is fairly easy.
Check this similar question. might help.
I have a mapview page that displays the current location in the map.
I am using MyLocationOverlay for the purpose. The code for that goes as follows:
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
geopoint = myLocationOverlay.getMyLocation();
ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable);
try{
overlayitem = new OverlayItem(geopoint, "", "");
}
catch(Exception e){
e.printStackTrace();
}
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapController.animateTo(geoPoint);
}
});
The above code works and gets the current location through gps and sets a marker at that point.
But the code inside try block is the issue.
I am getting null value inside geopoint.
Actually I have to get that point and do some calculations with distance and all. For that I have to get the correct value inside that geopoint.
Can anyone please tell the solution for this?
I've been working on the same problem for a day now and here's what I've discovered. For some reason this works
LocationManager lm;
GeoPoint gp;
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLoc != null){
int longTemp = (int)(lastKnownLoc.getLongitude()* 1000000);
int latTemp = (int)(lastKnownLoc.getLatitude() * 1000000);
gp = new GeoPoint(latTemp, longTemp);
}
and this doesn't
gp = myLocOverlay.getMyLocation();
Tracking current location can be done by using MyLocationOverlay class and through LocationManager. Using MyLocationOverlay, the code below works..
MyLocationOverlay myLocationOverlay;
MapView mapView;
MapController mapcontroller;
OverlayItem overlayitem;
List<Overlay> mapoverlays;
GeoPoint geopoint;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentlocation);
mapView = (MapView) findViewById(R.id.map);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mapView.setStreetView(true);
mapView.setTraffic(true);
mapcontroller = mapView.getController();
mapoverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.ic_map_red);
mapView.invalidate();
getCurrentLocation();
}
public void getCurrentLocation(){
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable);
try {
latitude = myLocationOverlay.getMyLocation().getLatitudeE6();
longitude = myLocationOverlay.getMyLocation().getLongitudeE6();
geopoint = new GeoPoint((int) (latitude), (int) (longitude));
overlayitem = new OverlayItem(geopoint, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapoverlays.add(itemizedoverlay);
mapcontroller.animateTo(geopoint);
mapcontroller.setZoom(16);
}
catch (Exception e) {}
}
});
}
If you override:
onLocationChanged();
Remember to call:
super.onLocationChanged();
after or before your own code. This appears to ensure that the variable
getMyLocation()
returns is not null.
The friend upstairs made me rise that try override nothing, neither draw nor drawMyLocation.
Just like this:
MyLocationOverlay myLocationOverlay = new SelfLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
myLocationOverlay.disableCompass();
mapView.getOverlays().add(myLocationOverlay);