How to update the marker whenever user touch on screen? - android

public void pointLocation(){
if(gmap!=null){
gmap.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latlng) {
// TODO Auto-generated method stub
double lat = latlng.latitude;
double lng = latlng.longitude;
mVisible=gmap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)));
Toast.makeText(getApplicationContext(), "Latitude :"+" "+lat+"Longitude :"+" "+lng, Toast.LENGTH_LONG).show();
}
});
mVisible.setVisible(false);//marker setVisible off so that old marker get destroy and new get appear
}
}

package com.sample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sample.R;
public class MainActivity extends FragmentActivity {
GoogleMap gmap;
// GPSTracker gpsTracker;
SupportMapFragment mapFragment;
Marker mVisible;
boolean checkCall = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.selectlocation);
// gpsTracker = new GPSTracker(this);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.maplocation);
userPosition();
pointLocation();
}
public void userPosition() {
gmap = mapFragment.getMap();
if (gmap != null) {
// if (gpsTracker.canGetLocation()) {
// double latCurrentloc = gpsTracker.getLatitude();
// double lngCurrentloc = gpsTracker.getLongitude();
LatLng pointer = new LatLng(17.2145632, 8.2345876);
gmap.addMarker(new MarkerOptions().position(pointer).title(
"Hello world"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(pointer).zoom(12).build();
gmap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// }
}
}
public void pointLocation() {
if (gmap != null) {
// mVisible.setVisible(true);
gmap.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latlng) {
if (checkCall) {
double lat = latlng.latitude;
double lng = latlng.longitude;
mVisible = gmap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng)));
Toast.makeText(
getApplicationContext(),
"Latitude :" + " " + lat + "Longitude :" + " "
+ lng, Toast.LENGTH_LONG).show();
checkCall = false;
}
}
});
}
}
}

Related

Unable to see marker on map

Below is my MapsActivity.java,
I'm trying to getCurrentLocation and place the marker there.
When I run app I am unable to see the marker on my map. What went wrong?
Thanks for the help.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.bustracker.usc.myapplication.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager manager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("INSIDE ONCREATE", "TRUE");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//get the location service
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
//request the location update thru location manager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
Log.d("BFORE ISPROVIDERENABLED", "TRUE");
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.d("LATLNG", latitude+" " +longitude);
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality() + ":";
result += addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}else if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality() + ":";
result += addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
protected void onPause() {
super.onPause();
manager.removeUpdates(locationListener);
Log.i("onPause...","paused");
}
}
Above is my MapsActivity.java,
I'm trying to getCurrentLocation and place the marker there.
When I run app I am unable to see the marker on my map. What went wrong?
Thanks for the help.
Try to create the markers and all things about the map inside the onMapReady method, if it doesn't work try seeing if you are getting your location properly
Hope it helps you, Pd: sorry for my english
Make sure you are getting valid latLng
OR
If you want to add custom icon to set marker add it like:
map.addMarker(new MarkerOptions().position(latLng).title(result)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

what is wrong with this piece of code?i am getting "null pointer exception".code is about drawing route on map [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
private String getMapsApiDirectionsUrl() {
String origin;
String destination=String.valueOf(l.longitude)+","+String.valueOf(l.latitude);
origin=String.valueOf(longitude)+","+String.valueOf(latitude);
// String url = "https://maps.googleapis.com/maps/api/directions/"+ output + "?" + params;
String url="https://maps.googleapis.com/maps/api/directions/json?origin="+origin+"&destination="+destination+"&sensor=false";
return url;
}
I am getting NullPointerException. I know what it is but not able to identify what is causing it. Assuming everything outside this method is correct, what is wrong syntactically?
This is my entire code:
package autogenie.maptrial;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class MainActivity extends FragmentActivity implements LocationListener,GoogleMap.OnMarkerDragListener {
private double latitude, longitude;
public GoogleMap googleMap,googleMap1;
LocationManager locationManager;
Button addressButton;
PlaceAutocompleteFragment fragment;
LatLng l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = supportMapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
addressButton = (Button) findViewById(R.id.addressButton);
fragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
addressButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.enter_place_name);
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
l= getLocationFromAddress(getApplicationContext(), address);
MarkerOptions a=new MarkerOptions().position(l);
Marker m=googleMap.addMarker(a);
m.setPosition(l);
}
});
fragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) { // Handle the selected Place
}
#Override
public void onError(Status status) { // Handle the error
}
});
}
public LatLng getLocationFromAddress(Context context,String strAddress) {
Geocoder coder = new Geocoder(context,Locale.getDefault());
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 1);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
} catch (Exception ex) {
ex.printStackTrace();
}
return p1;
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
Toast.makeText(getApplicationContext(),locationAddress,Toast.LENGTH_LONG).show();
}
}
#Override
public void onLocationChanged(Location location) {
if (location == null) {
latitude = 28.608426;
longitude = 77.225168;
} else {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
String s = "longitude:" + longitude + "latitude:" + latitude;
Log.i("Current location", " latlong value" + s);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Hello world"));
/*CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(latitude,
-longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(10);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
//dfg
private String getMapsApiDirectionsUrl() {
// String url = "https://maps.googleapis.com/maps/api/directions/"+ output + "?" + params;
String url="https://maps.googleapis.com/maps/api/directions/json?origin="+l+"&destination="+latitude+","+longitude+"&sensor=false";
return url;
}
private class ReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
}
class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public String result1,result2;
public void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List
addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
}
Stack Trace:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.google.maps.api.android.lib6.e.aw.<init>(Unknown Source)
at com.google.maps.api.android.lib6.e.ev.a(Unknown Source)
at com.google.android.gms.maps.internal.j.onTransact(SourceFile:137)
at android.os.Binder.transact(Binder.java:310)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addPolyline(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addPolyline(Unknown Source)
at autogenie.maptrial.MainActivity$ParserTask.onPostExecute(MainActivity.java:315)
at autogenie.maptrial.MainActivity$ParserTask.onPostExecute(MainActivity.java:267)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method) 01-21 12:24:35.291 3683-3683/autogenie.maptrial I/Process: Sending signal. PID: 3683 SIG: 9
one of your variables(l, latitude, longitude) is null since the only place that might cause the exception is the valueOf calls.

The method fromPixels(int, int) is undefined for the type Projection & The method getLatitudeE6() is undefined for the type GeoPoint

It is not working on fromPixels() & on getLatitudeE6() *getLongitudeE6()* at
public boolean onTouchEvent(MotionEvent event, MapView mapView)
method,which is situated at the last portion of this code.Can any one help plz.....
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity<GeoPoint, OverlayItem> extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
//private GeoPoint p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
/*................. Add this method ........*/
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = googleMap.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = (geopoint).getLatitudeE6() / 1E6;
// longitude
double lon = (geopoint).getLongitudeE6() / 1E6;
Toast.makeText(getBaseContext(), "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
}
}

get address corresponding to lattitude and longitude in google map api v2

Hi in my application i am getting the lattitude and longitude of a location.I want to convert that points into address, when i try to do so iam getting error
java.io.IOException: Service not Available at android.location.Geocoder.getFromLocation(Geocoder.java:136)
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class MapActivity extends FragmentActivity {
private GoogleMap map;
//Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GpsMapLocationActivity();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsMapLocationActivity implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
/*final GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));*/
/* String address = ConvertPointToLocation(point);address.toString();
Log.i("ADRESSS", ""+point);*/
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng loca=new LatLng(latitude,longitude);
String address = ConvertPointToLocation(loca);
address.toString();
Toast.makeText(getApplicationContext(),"" +loca,
Toast.LENGTH_LONG).show();
Log.i("Adress",""+address);
CameraPosition cmp= new CameraPosition.Builder().target(loca).zoom(14).bearing(90).tilt(30).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cmp));
MarkerOptions marker = new MarkerOptions()
.position(loca)
.title("MyMap")
.snippet("My Map View")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_gps));
map.addMarker(marker);
}
}
private String ConvertPointToLocation(LatLng loca) {
// TODO Auto-generated method stub
String address = "";
Geocoder geoCoder=new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
loca.latitude ,
loca.longitude, 1);
if (addresses.size() > 0) {
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#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
}
}
}
I am tried some codes but the error is repeating
plz help me thanks in advance..

Convert Latitude and longitude value to address in google map api v2

In my application i am getting the latitude and longitude value, i want it to convert into corresponding address.But when i do so i am getting error
java.io.IOException: Service not Available at android.location.Geocoder.getFromLocation(Geocoder.java:136)
This is my code
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class MapActivity extends FragmentActivity {
private GoogleMap map;
//Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GpsMapLocationActivity();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsMapLocationActivity implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
/*final GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));*/
/* String address = ConvertPointToLocation(point);address.toString();
Log.i("ADRESSS", ""+point);*/
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng loca=new LatLng(latitude,longitude);
String address = ConvertPointToLocation(loca);
address.toString();
Toast.makeText(getApplicationContext(),"" +loca,
Toast.LENGTH_LONG).show();
Log.i("Adress",""+address);
CameraPosition cmp= new CameraPosition.Builder().target(loca).zoom(14).bearing(90).tilt(30).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cmp));
MarkerOptions marker = new MarkerOptions()
.position(loca)
.title("MyMap")
.snippet("My Map View")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_gps));
map.addMarker(marker);
}
}
private String ConvertPointToLocation(LatLng loca) {
// TODO Auto-generated method stub
String address = "";
Geocoder geoCoder=new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
loca.latitude ,
loca.longitude, 1);
if (addresses.size() > 0) {
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#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
}
}
}
Thanks in advance..
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
myMap = fm.getMap();
// myMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
final Location location = locationManager
.getLastKnownLocation(provider);
latitude = location.getLatitude();
longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(MainActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentloc = myMap.addMarker(new MarkerOptions()
.position(latLng)
.title(add)
.snippet("" + latitude + "," + "" + longitude)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.locdot)));
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(11), 2000, null);
loc = (ImageButton) findViewById(R.id.loc);
loc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (location != null) {
onLocationChanged(location);
}
}
});
locationManager.requestLocationUpdates(provider, 20000, 0, this);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
myMap = fm.getMap();
// myMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
final Location location = locationManager
.getLastKnownLocation(provider);
latitude = location.getLatitude();
longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(MainActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentloc = myMap.addMarker(new MarkerOptions()
.position(latLng)
.title(add)
.snippet("" + latitude + "," + "" + longitude)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.locdot)));
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(11), 2000, null);
loc = (ImageButton) findViewById(R.id.loc);
loc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (location != null) {
onLocationChanged(location);
}
}
});
locationManager.requestLocationUpdates(provider, 20000, 0, this);
You need reboot your device and Geocoder will work.

Categories

Resources