My code is working very fine but there is problem of google places marker it doesnot show any result when i tried to find near by places at my drawn space even it doesnot show any type of exception or error during runtime .This is my code and image can anyone help me out to overcome it
public class MainActivity extends FragmentActivity implements LocationListener,OnTouchListener{
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
double firstlat,firstlong,lastlat,lastlong,cordlat,cordlong;
int index=1;
List<Address> addresses;
//double mLatitude=24.941698263434223;
// double mLongitude=77.44182396680117;
LatLng lastPoint, geoPoint ,firstGeoPoint;
private static final String TAG = "polygon";
private View mMapShelterView;
private GestureDetector mGestureDetector;
private ArrayList<LatLng> mLatlngs = new ArrayList<LatLng>();
private PolylineOptions mPolylineOptions;
private PolygonOptions mPolygonOptions;
// flag to differentiate whether user is touching to draw or not
private boolean mDrawFinished = false;
private boolean flag=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapShelterView = findViewById(R.id.drawer_view);
mGestureDetector = new GestureDetector(this, new GestureListener());
mMapShelterView.setOnTouchListener(this);
initilizeMap();
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
for(int i=0;i<mLatlngs.size();i++)
{
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
//sb.append("location="+mLatitude+","+mLongitude);
//sb.append("location="+firstlat+","+firstlong);
sb.append("location="+mLatlngs.get(i).latitude+","+mLatlngs.get(i).longitude);
System.out.println("D:>> out"+"location="+mLatlngs.get(i).latitude+","+mLatlngs.get(i).longitude);
sb.append("&radius=50000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("Browser KEY");
sb.append("&hasNextPage=true");
sb.append("&nextPage()=true");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
//System.out.println("placestask....."+ placesTask.execute(sb.toString()));
}
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
//mGoogleMap.clear();
for(int i=0;i<list.size();i++){
System.out.print("H:>> looping " +i);
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
System.out.println("m..."+ mGoogleMap.addMarker(markerOptions));
}
}
}
private final class GestureListener extends SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
}
/**
* Ontouch event will draw poly line along the touch points
*
*/
#Override
public boolean onTouch(View v, MotionEvent event) {
int X1 = (int) event.getX();
int Y1 = (int) event.getY();
Point point = new Point();
point.x = X1;
point.y = Y1;
LatLng firstGeoPoint = mGoogleMap.getProjection().fromScreenLocation(
point);
firstlat=firstGeoPoint.latitude;
firstlong=firstGeoPoint.longitude;
Log.d(TAG, "firstgeopoint:"+firstGeoPoint );
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
if (mDrawFinished) {
X1 = (int) event.getX();
Y1 = (int) event.getY();
point = new Point();
point.x = X1;
point.y = Y1;
LatLng geoPoint = mGoogleMap.getProjection()
.fromScreenLocation(point);
mLatlngs.add(geoPoint);
//geopoint value
firstlat=geoPoint.latitude;
firstlong=geoPoint.longitude;
//last latitude and longitude
LatLng lastPoint = mLatlngs.get(mLatlngs.size() - 1);
lastlat=lastPoint.latitude;
lastlong=lastPoint.longitude;
mPolylineOptions = new PolylineOptions();
mPolylineOptions.color(Color.RED);
mPolylineOptions.width(3);
mPolylineOptions.addAll(mLatlngs);
mGoogleMap.addPolyline(mPolylineOptions);
Log.d(TAG,"geopoint :"+geoPoint);
}
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "Poinnts array size " + mLatlngs.size());
mLatlngs.add(firstGeoPoint);
mGoogleMap.clear();
mPolylineOptions = null;
mMapShelterView.setVisibility(View.GONE);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
mPolygonOptions = new PolygonOptions();
mPolygonOptions.fillColor(0x7F00FF00);
mPolygonOptions.strokeColor(Color.RED);
mPolygonOptions.strokeWidth(5);
mPolygonOptions.addAll(mLatlngs);
mGoogleMap.addPolygon(mPolygonOptions);
mDrawFinished = false;
Log.d(TAG,"latitude and longitude:"+mLatlngs);
//looping through coordinates
/* for (int i=0;i>=mLatlngs.size();i++){
LatLng ltln=mLatlngs.get(i);
cordlat=ltln.latitude;
cordlong=ltln.longitude;
} */
break;
}
return mGestureDetector.onTouchEvent(event);
}
/**
* Setting up map
*
*/
private void initilizeMap() {
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (status == ConnectionResult.SUCCESS) {
if (mGoogleMap == null) {
mGoogleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mGoogleMap.setMyLocationEnabled(true);
}
} else if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
// showErrorDialog(status);
} else {
Toast.makeText(this, "No Support for Google Play Service",
Toast.LENGTH_LONG).show();
}
}
/**
* Method gets called on tap of draw button, It prepares the screen to draw
* the polygon
*
* #param view
*/
public void drawZone(View view) {
mGoogleMap.clear();
mLatlngs.clear();
mPolylineOptions = null;
mPolygonOptions = null;
mDrawFinished = true;
mMapShelterView.setVisibility(View.VISIBLE);
mGoogleMap.getUiSettings().setScrollGesturesEnabled(false);
}
public synchronized boolean Contains(Location location) {
boolean isInside = false;
if (mLatlngs.size() > 0) {
LatLng lastPoint = mLatlngs.get(mLatlngs.size() - 1);
double x = location.getLongitude();
for (LatLng point : mLatlngs) {
double x1 = lastPoint.longitude;
double x2 = point.longitude;
double dx = x2 - x1;
if (Math.abs(dx) > 180.0) {
if (x > 0) {
while (x1 < 0)
x1 += 360;
while (x2 < 0)
x2 += 360;
} else {
while (x1 > 0)
x1 -= 360;
while (x2 > 0)
x2 -= 360;
}
dx = x2 - x1;
}
if ((x1 <= x && x2 > x) || (x1 >= x && x2 < x)) {
double grad = (point.latitude - lastPoint.latitude) / dx;
double intersectAtLat = lastPoint.latitude
+ ((x - x1) * grad);
if (intersectAtLat > location.getLatitude())
isInside = !isInside;
}
lastPoint = point;
}
}
return isInside;
}
/* public GeoPoint getLocationFromAddress(String strAddress){
Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;
try {
// address = coder.getFromLocationName(mLatlngs);
address = coder.getFromLocation(mLatlngs, 10);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
}catch(Exception e){
Log.d(TAG, "exception throw");
}
return p1;
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
//LatLng latLng = new LatLng(firstlat, firstlong);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#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
}
}
This is my image when i tried to search near by places at my drawn space it doesnot drop any marker there not even showing error can somebody help me out plss....
Thanks in Advance
you can try the new Android Places API, which states,
"If you want to change the place picker's default behavior, you can use the builder to set the initial latitude and longitude bounds of the map displayed by the place picker. Call setLatLngBounds() on the builder, passing in a LatLngBounds to set the initial latitude and longitude bounds. These bounds define an area called the 'viewport'. By default, the viewport is centered on the device's location, with the zoom at city-block level."
https://developers.google.com/places/android/placepicker
You can create a LatLngBounds by using the including(LatLng point) method. See the below page for more details.
https://developer.android.com/reference/com/google/android/gms/maps/model/LatLngBounds.html
Related
I got the correct souce and destination latitude and longitude in map but I am able to drwa line between Source and destination but this line is strait line display in map between source and destination marker. Destination Latitide and Destination Longitude are fetch successfully from Server.
But I want to Draw line between source and destination Like this below.
This is Example.
Google Map is also Display CurrectPosition of Source and Destination.
How can it Possible?
Please Guide me.
Please Help me.
Thank you.
My Code is,
public class Map extends FragmentActivity {
GoogleMap googleMap;
SupportMapFragment fm;
double myLat = 23.0137759;
double destLat = 0.0;
double myLng = 72.5158836;
double destLng = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigate_to_me_map);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Intent intent = getIntent();
destLat = intent.getDoubleExtra("latitude", 0.0);
destLng = intent.getDoubleExtra("longitude", 0.0);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
this, requestCode);
dialog.show();
} else {
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.fullmap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
}
googleMap
.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
public void onMyLocationChange(Location location) {
// TODO Auto-generated method stub
myLat = location.getLatitude();
myLng = location.getLongitude();
}
});
drawRoutePath(strAddressOne);
}
}
private void drawRoutePath(String searchText) {
try {
// find current address latlong and true than draw route
// between to points or current loction and search
// address
googleMap.clear();
if (myLat != 0 && myLng != 0) {
LatLng origin = new LatLng(myLat, myLng);
drawMarker(origin);
LatLng dest = new LatLng(destLat, destLng);
drawMarker(dest);
Polyline line = googleMap.addPolyline(new PolylineOptions()
.add(origin, dest).width(5).color(Color.RED));
} else {
Toast.makeText(getApplicationContext(),
"Current Location does not found",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
// TODO: handle exception
Log.e("Second ", "drawRoutePath errro " + e.toString());
}
}
private void drawMarker(LatLng point) {
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
googleMap.addMarker(new MarkerOptions().position(point).visible(true))
.showInfoWindow();
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
point.latitude, point.longitude), 6f));
}
}
Here's the source code to draw a route between the source and destination :
public class MapActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private SupportMapFragment mapFragment;
private GoogleMap map;
private GoogleApiClient mGoogleApiClient;
ArrayList markerPoints;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 15000; /* 15 secs */
private long FASTEST_INTERVAL = 5000; /* 5 secs */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_map);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_actionbar_maps);
markerPoints = new ArrayList();
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
if (mapFragment != null) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap map) {
loadMap(map);
}
});
} else {
Toast.makeText(this, "Error - Map Fragment was null!!", Toast.LENGTH_SHORT).show();
}
}
protected void loadMap(GoogleMap googleMap) {
map = googleMap;
if (map != null) {
// Map is ready
Toast.makeText(this, "Map Fragment was loaded properly!", Toast.LENGTH_SHORT).show();
map.setMyLocationEnabled(true);
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(markerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = (LatLng) markerPoints.get(0);
LatLng dest = (LatLng) markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
// Now that map has loaded, let's get our location!
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
connectClient();
} else {
Toast.makeText(this, "Error - Map was null!!", Toast.LENGTH_SHORT).show();
}
}
protected void connectClient() {
// Connect the client.
if (isGooglePlayServicesAvailable() && mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
/*
* Called when the Activity becomes visible.
*/
#Override
protected void onStart() {
super.onStart();
connectClient();
}
/*
* Called when the Activity is no longer visible.
*/
#Override
protected void onStop() {
// Disconnecting the client invalidates it.
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
/*
* Handle results returned to the FragmentActivity by Google Play services
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mGoogleApiClient.connect();
break;
}
}
}
// Fetches data from url passed
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
Toast.makeText(this, "GPS location was found!", Toast.LENGTH_SHORT).show();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 16);
map.animateCamera(cameraUpdate);
//marker = map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.vehicle_marker)).flat(true).anchor(0.5f,0.5f));
startLocationUpdates();
} else {
Toast.makeText(this, "Current location was null, enable GPS on emulator!", Toast.LENGTH_SHORT).show();
}
}
protected void startLocationUpdates() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
public void onLocationChanged(Location location) {
// Report to the UI that the location was updated
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
/* if(marker == null){
*//* marker.remove();*//*
marker = map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.vehicle_marker)));
}
marker.setPosition(latLng);
*/
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 16);
map.animateCamera(cameraUpdate);
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
#Override
public void onConnectionSuspended(int i) {
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
}
}
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#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]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
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);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
DirectionsJSONParser.java is given below :
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l <list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
You can use below library:
Google-Directions-Android
I followed a tutorial from;
http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
The google places aspect works perfect but the google map code is outdated. Im not sure how to update google map code from v1 to v2?
Any pointers??
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = geopoint.getLatitudeE6() / 1E6;
// longitude
double lon = geopoint.getLongitudeE6() / 1E6;
//Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
}
public void populateNow(){
this.populate();
}
}
public class NearbyActivity extends Activity{
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Places List
PlacesList nearPlaces;
// GPS Location
GPSTracker gps;
// Button
Button btnShowOnMap;
// Progress dialog
ProgressDialog pDialog;
// Places Listview
ListView lv;
// ListItems data
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
Button buttonNear = (Button) findViewById(R.id.buttonNearby);
buttonNear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Starting a new Intent
Intent HomeScreen = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(HomeScreen);
}
});
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(NearbyActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(NearbyActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
// Getting listview
lv = (ListView) findViewById(R.id.list);
// button show on map
btnShowOnMap = (Button) findViewById(R.id.btn_show_map);
// calling background Async task to load Google Places
// After getting places from Google all the data is shown in listview
new LoadPlaces().execute();
/** Button click event for shown on map */
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
/**
* ListItem click event
* On selecting a listitem SinglePlaceActivity is launched
* */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlaceActivity.class);
// Sending place refrence id to single place activity
// place refrence id used to get "Place full details"
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearbyActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = null; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 400; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(NearbyActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(NearbyActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
I'm developing an android Google map app. How to create a current location ,balloon overlay and other marker location points.
I am creating Other marker location points in (CustomMap.java)
Here I want to current location also.Please help me
CustomMap.java
public class CustomMap extends MapActivity implements LocationListener {
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
Drawable drawable2;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay2;
double longitude;
double latitude;
long start;
long stop;
int x, y;
int lati = 0;
int longit = 0;
GeoPoint touchedPoint;
public boolean overlay_status=false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// making it full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_custom_map);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// first overlay
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
//first overlay in first pinpoint
GeoPoint point = new GeoPoint((int)(13.0094444*1E6),(int)(77.5508333*1E6));
CustomOverlayItem overlayItem = new CustomOverlayItem(point, "ISKCON Temple Bangalore(1997)",
"(ISKCON Temple, Chord Rd, Mahalakshmipuram Layout, Nagapura, Bangalore, Karnataka, India)",
"http://www.iskcon-bda.org/data/HKH.jpg");
itemizedOverlay.addOverlay(overlayItem);
//first overlay in second pinpoint
GeoPoint point2 = new GeoPoint((int)(12.8008*1E6),(int)(77.5756*1E6));
CustomOverlayItem overlayItem2 = new CustomOverlayItem(point2, "Bannerghatta National Park",
"(Bannerghatta Biological Park is carved out of the Bannerghatta National Park in the year 2002)",
"http://www.google.co.in/imgres?imgurl=http://travel.sulekha.com/" +
"india/karnataka/bangalore/photos/bannerghatta-national-park-25.jpg&imgrefurl=http://travel.sulekha.com/" +
"a-visit-to-bannerghatta-national-park_bangalore-travelogue-3541.htm&h=194&w=259&sz=1&tbnid=K5TNPwXHgihgRM:&tbnh=" +
"119&tbnw=160&zoom=1&usg=__MFNGL1C2InXP7jw7XmEi4ym45NY=&docid=d78iF3T5ditWeM&itg=1&hl=en&sa=X&ei=" +
"CpwQUdOmHIPUrQe0m4H4Bg&sqi=2&ved=0CHwQ_B0wCw");
itemizedOverlay.addOverlay(overlayItem2);
mapOverlays.add(itemizedOverlay);
// second overlay
drawable2 = getResources().getDrawable(R.drawable.marker2);
itemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable2, mapView);
//second overlay in third pinpoint
GeoPoint point3 = new GeoPoint((int)(12.8339956*1E6),(int)(77.4009816*1E6));
CustomOverlayItem overlayItem3 = new CustomOverlayItem(point3, "Wonderla Bangalore(2005)",
"(Wonderla is an amusement park located near Bidadi, 28 kilometres Bangalore, spanning 82 acres of land)",
"http://www.google.co.in/imgres?imgurl=http://www.yohyoh.com/places-tourism/pictures/wb3.jpg&imgrefurl=http://" +
"www.yohyoh.com/places-tourism/view.php/popular-tours/Karnataka/Bangalore/wonderla-bangalore/561/8192987807&h=" +
"194&w=259&sz=1&tbnid=RoLC5gzRHP6VSM:&tbnh=160&tbnw=213&zoom=1&usg=__ShDQAmQ0zjQaKbsy0A63BokHAmk=" +
"&docid=J1aN09WXjvHw4M&itg=1&hl=en&sa=X&ei=Sp0QUbvIEMHjrAfTy4GgBA&ved=0CNMBEPwdMAo");
itemizedOverlay2.addOverlay(overlayItem3);
//second overlay in third pinpoint
GeoPoint point4 = new GeoPoint((int)(12.8385923*1E6),(int)(77.661710599*1E6));
CustomOverlayItem overlayItem4 = new CustomOverlayItem(point4, "Wipro Technologies,Bangalore",
"(Wipro Technologies, Electronics City Phase 1, Electronics City, Bangalore, Karnataka 560100, India)",
"http://www.electronic-city.in/companies/profile/wipro/wipro-electronic-city.jpg");
itemizedOverlay2.addOverlay(overlayItem4);
mapOverlays.add(itemizedOverlay2);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
latitude = location.getLatitude();
// Getting longitude
longitude = location.getLongitude();
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point5 = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
tvLocation.setText("Address :" + address );
}
catch (IOException e) {
e.printStackTrace();
}
drawable = getResources().getDrawable(R.drawable.url);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
mapView.getOverlays().add(itemizedOverlay);
itemizedOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mapView.getOverlays().add(itemizedOverlay);
}
});
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point5);
itemizedOverlay.enableMyLocation();
mapView.postInvalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
CustomOverlayItem currentLocation = new CustomOverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude, null);
// Adding the mark to the overlay
itemizedOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
mapOverlays.add(itemizedOverlay);
if (savedInstanceState == null) {
//Contains Displaying the pinpoint
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
}else {
// example restoring focused state of overlays
int focused;
focused = savedInstanceState.getInt("focused_1", -1);
if (focused >= 0) {
itemizedOverlay.setFocus(itemizedOverlay.getItem(focused));
}
focused = savedInstanceState.getInt("focused_2", -1);
if (focused >= 0) {
itemizedOverlay2.setFocus(itemizedOverlay2.getItem(focused));
}
}
Touchy t = new Touchy();
mapOverlays = mapView.getOverlays();
mapOverlays.add(t);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// example saving focused state of overlays
if (itemizedOverlay.getFocus() != null) outState.putInt("focused_1", itemizedOverlay.getLastFocusedIndex());
if (itemizedOverlay2.getFocus() != null) outState.putInt("focused_2", itemizedOverlay2.getLastFocusedIndex());
super.onSaveInstanceState(outState);
}
//Contains creating the option menu items
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 1, "Remove Overlay");
menu.add(0, 1, 1, "set Overlay");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.drawable.home_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(overlay_status==false)
{
menu.findItem(1).setVisible(false);
menu.findItem(0).setVisible(true);
//overlay_status=true;
}
else
{
menu.findItem(0).setVisible(false);
menu.findItem(1).setVisible(true);
// overlay_status=false;
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home1:
finish();
return true;
case 0:
//Toast.makeText(getApplicationContext(), "remove overlay ", Toast.LENGTH_SHORT).show();
// example hiding balloon before removing overlay
if (itemizedOverlay.getFocus() != null) {
itemizedOverlay.hideBalloon();
}
mapOverlays.remove(itemizedOverlay);
mapView.invalidate();
overlay_status=true;
return true;
case 1:
Toast.makeText(getApplicationContext(), "set overlay ", Toast.LENGTH_SHORT).show();
if (itemizedOverlay.getFocus() != null) {
itemizedOverlay.getBalloonBottomOffset();
}
mapOverlays.add(itemizedOverlay);
mapView.bringToFront();
overlay_status=false;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Touchy extends Overlay{
List<Address> address;
String display = "";
String display1;
#SuppressWarnings({ "deprecation" })
public boolean onTouchEvent(MotionEvent e,MapView m){
if(e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int)e.getX();
y = (int)e.getY();
touchedPoint = mapView.getProjection().fromPixels(x, y);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if(address.size() > 0){
for(int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG).show();
}
}catch(IOException e1){
}
finally
{
display1=display;
display=" ";
}
}
if(e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
/**contains the creating a Alert Dialog Box (place apinpoint, get address, Toggle View)
* In Dialog Box Maximum three buttens
*/
if(stop - start > 1000){
AlertDialog alert = new AlertDialog.Builder(CustomMap.this).create();
alert.setTitle("pick an Option");
alert.setMessage("I told to pick an option");
alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CustomOverlayItem overlayItem = new CustomOverlayItem(touchedPoint,"Address:",display1, display1);
// SimpleItemizedOverlay itemizedOverlay = new SimpleItemizedOverlay(drawable, mapView);
CustomItemizedOverlay<CustomOverlayItem> itemOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
// CustomPinpoint custom = new CustomPinpoint(drawable, CustomMap.this);
// custom.insertPinpoint(overlayItem);
itemOverlay.insertPinpoint(overlayItem);
itemOverlay.addOverlay(overlayItem);
mapOverlays.add(itemOverlay);
}
});
alert.setButton2("get address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if(address.size() > 0){
String display = "";
for(int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG).show();
}
}catch(IOException e){
}
}
});
alert.setButton3("Toggle View", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mapView.isSatellite()){
mapView.setSatellite(false);
mapView.setStreetView(true);
}else{
mapView.setStreetView(false);
mapView.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
public void onLocationChanged(Location location) {
lati = (int) (location.getLatitude() * 1E6);
longit = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longit);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up?", "2nd String");
CustomPinpoint custom = new CustomPinpoint(drawable, CustomMap.this);
custom.insertPinpoint(overlayItem);
mapOverlays.add(custom);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Try this AndroidHive Google code
Google Map Link Android Working with Google Places and Maps Tutorial
public class SinglePlaceActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Place Details
PlaceDetails placeDetails;
// Progress dialog
ProgressDialog pDialog;
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_place);
Intent i = getIntent();
// Place referece id
String reference = i.getStringExtra(KEY_REFERENCE);
// Calling a Async Background thread
new LoadSinglePlaceDetails().execute(reference);
}
/**
* Background Async Task to Load Google places
* */
class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SinglePlaceActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
String reference = args[0];
// creating Places class object
googlePlaces = new GooglePlaces();
// Check if used is connected to Internet
try {
placeDetails = googlePlaces.getPlaceDetails(reference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
if(placeDetails != null){
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if(status.equals("OK")){
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
Log.d("Place ", name + address + phone + latitude + longitude);
// Displaying all the details in the view
// single_place.xml
TextView lbl_name = (TextView) findViewById(R.id.name);
TextView lbl_address = (TextView) findViewById(R.id.address);
TextView lbl_phone = (TextView) findViewById(R.id.phone);
TextView lbl_location = (TextView) findViewById(R.id.location);
// Check for null data from google
// Sometimes place details might missing
name = name == null ? "Not present" : name; // if name is null display as "Not present"
address = address == null ? "Not present" : address;
phone = phone == null ? "Not present" : phone;
latitude = latitude == null ? "Not present" : latitude;
longitude = longitude == null ? "Not present" : longitude;
lbl_name.setText(name);
lbl_address.setText(address);
lbl_phone.setText(Html.fromHtml("<b>Phone:</b> " + phone));
lbl_location.setText(Html.fromHtml("<b>Latitude:</b> " + latitude + ", <b>Longitude:</b> " + longitude));
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}else{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
}
Try this,
mapView.getOverlays().add(locationoverlay);
locationoverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mapView.getOverlays().add(locationoverlay);
}
});
locationoverlay.enableMyLocation();
mapView.postInvalidate();
Above code will provide the current location in android default marker overlay
public class LocateActivity extends MapActivity {
MapView mapView = null;
Geocoder geocoder = null;
Drawable drawable = null;
Geocoder gc = null;
final CountDownLatch signal = new CountDownLatch(1);
String status;
double lat;
double lng;
public ArrayAdapter<String> adapter;
public AutoCompleteTextView filltt;
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; //
ProgressDialog pDialog;
PlacesList nearPlaces;
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
Drawable drawable_user;
Drawable drawablee;
String locnm;
GPSTracker gps;
GooglePlaces googlePlaces;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("My locale::"+Locale.getDefault().getDisplayLanguage());
filltt = (AutoCompleteTextView)findViewById(id.autoCompleteTextView1);
mapView = (MapView) findViewById(R.id.geoMap);
mapView.setBuiltInZoomControls(true);
mapView.setClickable(true);
mapOverlays = mapView.getOverlays();
gc = new Geocoder(this);
drawable = this.getResources().getDrawable(R.drawable.pon);
adapter = new ArrayAdapter<String>(this,R.layout.item_list);
adapter.setNotifyOnChange(true);
filltt.setAdapter(adapter);
filltt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(filltt.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
// map starting point
int lat = (int) (51.678383 * 1000000);
int lng = (int) (19.334822 * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(18);
mapView.getController().setCenter(pt);
final String lattt="23.0666";
final String loggg="72.6666";
Button geoBtn = (Button) findViewById(R.id.geocodeBtn);
// geoBtn.setText(Html.fromHtml("<b>Year:</b>2012,<b>Franch</b>"));
geocoder = new Geocoder(this);
geoBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
locnm = filltt.getText().toString();
if(locnm.length()==0){
Toast.makeText(LocateActivity.this, "Enter Location", Toast.LENGTH_LONG).show();
}
else
// EditText locale = (EditText) findViewById(R.id.location);
{
new LoadPlaces().execute();
String locationName = filltt.getText().toString();
Toast.makeText(LocateActivity.this, locationName, Toast.LENGTH_LONG).show();
System.out.println("location: "+locationName);
List<Address> addressList = geocoder.getFromLocationName(
locationName, 5);
System.out.println("first val: " + addressList.get(0));
System.out.println("Total Result: " + addressList.size());
if (addressList != null && addressList.size() > 0) {
int lat = (int) (addressList.get(0).getLatitude() * 1e6);
int lng = (int) (addressList.get(0).getLongitude() * 1e6);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
super.onConfigurationChanged(newConfig);
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>>
{
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(args[0].toString(), "UTF-8") +"&types=geocode&language=en&sensor=true&key=AIzaSyDYnuaL0x_7xGNqrEvYkgEB20_k-b4avOI");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
System.out.println("Line: "+line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
System.out.println(ja.length());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
#Override
protected void onPostExecute(ArrayList<String> result)
{
Log.d("YourApp", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
filltt.setAdapter(adapter);
for (String string : result)
{
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
class LoadPlaces extends AsyncTask<String, String, PlacesList> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LocateActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
#SuppressLint("NewApi")
protected PlacesList doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
if(gc.isPresent()){
List<Address> list = gc.getFromLocationName(locnm, 1);
Address address = list.get(0);
lat = address.getLatitude();
lng = address.getLongitude();
}
System.out.println("Lat Val: " + lat);
System.out.println("Long Val: " + lng);
String types = ""; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(lat,
lng, radius, types);
System.out.println("Places: "+nearPlaces);
// }
} catch (Exception e) {
e.printStackTrace();
}
return nearPlaces;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(PlacesList file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all products
pDialog.dismiss();
signal.countDown();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
System.out.println("Place Name: " +p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
System.out.println("ITEM: " + placesListItems.get(0));
}
}
}
else if(status.equals("ZERO_RESULTS")){
}
else if(status.equals("UNKNOWN_ERROR"))
{
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
}
else if(status.equals("REQUEST_DENIED"))
{
}
else if(status.equals("INVALID_REQUEST"))
{
}
else
{
}
}
});
try {
signal.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (lat * 1E6),
(int) (lng * 1E6));
// Drawable marker icon
Drawable drawable_user = getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
}
#Override
public boolean isLocationDisplayed() {
return false;
}
#Override
public boolean isRouteDisplayed() {
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you really want to Exit ?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
filltt.setText("");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
Note: this code run perfectly in android 4.0 but when i test it in android 2.3, it gives me force close error. and throws me error like
Service not available.. and latitude and longtitude values are 0.
what is the solution for that? Please, help me to get out of this.
I got the solution.
package com.example.locatebased;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import org.kxml.*;
import org.kxml.io.*;
import org.kxml.kdom.*;
import org.kxml.parser.*;
import android.util.Log;
public class Geocoding
{
Hashtable ht=null;
private boolean time=true;
private int count=0;
private String citystreetvalue=null;
public Geocoding()
{
System.out.println("Constructor call...");
ht=new Hashtable();
}
//***************************** Find Address of the latitude Longitude ***********
public String parseXml(String address)
{
try
{
System.out.println("Address is:" + address);
//URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=tagore%20road%20rajkot&sensor=false");
URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false");
Log.e("Url",mUrl.toString());
HttpURLConnection mConn = (HttpURLConnection) mUrl.openConnection();
System.out.println("After address add...");
InputStream is = mConn.getInputStream();
Reader reader = new InputStreamReader(is);
XmlParser parser = new XmlParser(reader);
traverse(parser,"");
mConn.disconnect();
is.close();
System.out.println("Close all connection...");
if(ht.get("status").toString().equals("OK"))
{
System.out.println("result is Ok..." + ht.get("locality").toString() );
citystreetvalue=ht.get("latitude").toString() + ","+ ht.get("longitude").toString() +","+ht.get("locality").toString();
}
else
{
System.out.println("result is not Ok...");
citystreetvalue="InvalidLocation";
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
System.out.println("before returen statement...");
return citystreetvalue;
}
public void traverse(XmlParser parser, String indent ) throws Exception
{
System.out.println("in Traverse method....");
boolean leave = false;
String title = new String();
String desc = new String();
do
{
ParseEvent event = parser.read ();
ParseEvent pe;
switch (event.getType())
{
// For example, <title>
case Xml.START_TAG:
// see API doc of StartTag for more access methods
// Pick up Title for display
if ("status".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
ht.put("status",title);
}
if(count<2)
{
if ("lat".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
ht.put("latitude",title);
count=count+1;
}
if ("lng".equals(event.getName()))
{
pe = parser.read();
desc = pe.getText();
ht.put("longitude",desc);
count=count+1;
}
}
if ("long_name".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
}
if ("type".equals(event.getName()))
{
pe = parser.read();
desc = pe.getText();
if(desc.equals("route"))
{
System.out.println("street is:" + title);
ht.put("street",title);
}
}
if("formatted_address".equals(event.getName()))
{
if(time)
{
pe = parser.read();
title = pe.getText();
ht.put("address",title);
time=false;
}
}
ht.put(desc,title);
traverse(parser,"") ; // recursion call for each <tag></tag>
break;
// For example </title?
case Xml.END_TAG:
leave = true;
break;
// For example </rss>
case Xml.END_DOCUMENT:
leave = true;
break;
// For example, the text between tags
case Xml.TEXT:
break;
case Xml.WHITESPACE:
break;
default:
}
} while( !leave );
}
}
now add below code in mainactivity class:
geocoding=new Geocoding();
locnm=locnm.replace(" ","%20");
String citystreetvalue=geocoding.parseXml(locnm);
System.out.println("string is:" + citystreetvalue);
if(citystreetvalue.equals("InvalidLocation"))
{
}else
{
String citystreetval[]=Split(citystreetvalue, ",");
String latstreet=citystreetval[2];
nlatitude=citystreetval[0];
nlongitude=citystreetval[1];
}
// here is my code of MapActivity class
public class MapActivity extends com.google.android.maps.MapActivity implements LocationListener
{
MapView mapView;
MapController mc;
GeoPoint p;
MyLocation myLocation = new MyLocation();
LocationManager mlocManager;
int distance;
public void onCreate(Bundle savedInstanceState) {
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
ImageButton mpl = (ImageButton)findViewById(R.id.nearbybuttn);
mapView = (MapView) findViewById(R.id.mv);
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mc = mapView.getController();
mc.setZoom(8);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 200,
0, mlocListener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// gets current location on position change
loc.getLatitude();
loc.getLongitude();
Double slat = loc.getLatitude();
Double slon = loc.getLongitude();
TextView txlat = (TextView) findViewById(R.id.lat);
TextView txlon = (TextView) findViewById(R.id.lon);
txlat.setText(slat + "n");
txlon.setText(slon + "n");
// json retrieval
JSONObject j2 = JSONfunctions
.getJSONfromURL("/merchant/apis/?device=iphone&api=store_details");
try {
JSONArray myID = j2.getJSONArray("stores");
for (int i = 0; i < myID.length(); i++) {
Log.v("state", "json address being read");
JSONObject j3 = myID.getJSONObject(i);
String name = j3.getString("Address");
String id = j3.getString("StoreId");
Log.v("id", id);
Log.v("Address", name);
JSONObject j4 = j3.getJSONObject("Address");
Double jlat = j4.getDouble("Latitude");
Double jlon = j4.getDouble("Longitude");
Log.v("Latitude", jlat + "n");
Log.v("Longitude", jlon + "n");
// Get the distance between lat long
Location locationA = new Location("point A");
locationA.setLatitude(slat);
locationA.setLongitude(slon);
Location locationB = new Location("point B");
locationB.setLatitude(jlat);
locationB.setLongitude(jlon);
distance = (int) locationA.distanceTo(locationB);
String str = " (" + String.valueOf(distance) + " meters)";
Log.v("Distance", str);
// adjust drawable params
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
Drawable user = getResources().getDrawable(
android.R.drawable.arrow_down_float);
int userWidth = user.getIntrinsicWidth();
int userHeight = user.getIntrinsicHeight();
user.setBounds(0, userHeight, userWidth, 0);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
// refernc to overlay class
LocationOverlay myItemizedOverlay = new LocationOverlay(
marker, MapActivity.this);
LocationOverlay myItemizedOverlay1 = new LocationOverlay(
user, MapActivity.this);
mapView.getOverlays().add(myItemizedOverlay);
mapView.getOverlays().add(myItemizedOverlay1);
// create geopoint for user
GeoPoint usr = new GeoPoint((int) (slat * 1e6),
(int) (slon * 1e6));
// add overlay(user) to user's location
myItemizedOverlay1.addItem(usr, "User");
mc.animateTo(usr);
// create geopoint for json
GeoPoint jgpt = new GeoPoint((int) (jlat * 1e6),
(int) (jlon * 1e6));
// add marker on geopoints from json
myItemizedOverlay.addItem(jgpt, "StoreId" + id);
mapView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
}
} catch (JSONException e) {
Log.e("loG_tag", "Error parsing" + e.toString());
}
}
private TextView findViewById(int lat) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Not Executing - What should we consider this as a Compile Time or a Runtime Error.
If yes paste the error logs. Also
Are You Trying this on Real Device ? If not do so
Is GPS of your device is ON ? if not do so
Try using 0 parameter instead of 200. See its results.
Also try LocationManager.NETWORK_PROVIDER
Make Sure You have sufficient permission defined in Manifest File.