Extracting STATUS code of Google Places API response - android

I am new to using JSON and I am having an issue figuring out how to extract the STATUS code from Google Places API response. I guess the issue is because it is a seperate root element from the results array. Here is my code for my parser:
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity="-NA-";
String latitude="";
String longitude="";
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}

Yes, status, results and html_attributions are the 3 root elements in google places api JSON response. You can extract the status data from the response like below:
String statuscheck = jObject.getString("status");

Related

How to use Google Places API to search for addresses/places? Android

I want to know how I can use a string to get search results for an address or a place using Google Places API. Currently, I'm using Geocoder to get search results but the results I am getting are not complete or relevant to my current location. Please be a little descriptive because I haven't used Google Places API before. I have read this tutorial
but I can't quiet understand it. I will have a string input from the user in an EditText view and I want to use that string to show a list of matching addresses which are relevant to my current location.
Hi here i'm giving you simple example about autocomplete, if you want you can try other from referring google api site. Just follow few steps. Hope this help you to understand and do your work easily
Step 1.
In you Activity you need to use edit text as text changed listener, then call places api
et_Search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
placesTask = new PlacesTask();
String[] toPass = new String[2];
toPass[0] = s.toString();
placesTask.execute(toPass);
}
});
Step 2.
here is calling for google places api
// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String> {
private String val = "";
#Override
protected String doInBackground(String... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key="+getResources().getString(R.string.google_server_key);
String input="";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String parameters = input+"&"+key + "&components=country:in";
// Output format +gpsTracker.getLatitude() + "," + gpsTracker.getLongitude() + "&radius=20000
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
try{
// Fetching the data from we service
data = Webservices.ApiCallGet(url);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Creating ParserTask
parserTask = new ParserTask();
String[] strData = new String[2];
strData[0] = result;
// Starting Parsing the JSON string returned by Web Service
parserTask.execute(strData);
}
}
Step 3. Getting Result
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
#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;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] from = new String[] { "description"};
int[] to = new int[] { android.R.id.text1 };
AutoCompleteAdapter adapter = new AutoCompleteAdapter(getBaseContext(), result);
// Setting the adapter
if(adapter != null && result != null )
lv_SearchList.setAdapter(adapter);
}
}
// Fetches latitude & longitude from place id
private class LatLongTask extends AsyncTask<Void, Void, String> {
private HashMap<String, String> placeMap;
private ProgressDialog dialog;
public LatLongTask(HashMap<String, String> placeMap){
this.placeMap = placeMap;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(SearchActivity.this, "", "Please Wait...",
true, false);
}
#Override
protected String doInBackground(Void... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key="+getResources().getString(R.string.google_server_key);
String input="";
try {
input = "placeid=" + URLEncoder.encode(placeMap.get("place_id"), "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// Building the parameters to the web service
String parameters = input+"&"+key ;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
try{
// Fetching the data from we service
data = Webservices.ApiCallGet(url);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(dialog!= null && dialog.isShowing()){
dialog.dismiss();
}
try {
JSONObject jResult = new JSONObject(result);
if(jResult.getString("status").equals("OK")) {
JSONObject jsonObject = jResult.getJSONObject("result");
JSONObject jGeometry = jsonObject.getJSONObject("geometry");
JSONObject jLocation = jGeometry.getJSONObject("location");
placeMap.put("lat", ""+jLocation.getString("lat"));
placeMap.put("lng", ""+jLocation.getString("lng"));
ArrayList<HashMap<String, String>> mapArrayList = new ArrayList<HashMap<String, String>>();
mapArrayList.add(placeMap);
Intent intent = new Intent();
intent.putExtra("result", mapArrayList);
if (getParent() == null) {
setResult(Activity.RESULT_OK, intent);
} else {
getParent().setResult(Activity.RESULT_OK, intent);
}
finish();
}else{
Utils.toastmessage(SearchActivity.this, "Please try again later.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Step 4. create this class
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("predictions");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String id="";
String reference="";
String description="";
String place_id = "";
try {
description = jPlace.getString("description");
id = jPlace.getString("id");
reference = jPlace.getString("reference");
place_id = jPlace.getString("place_id");
place.put("description", description);
place.put("_id",id);
place.put("reference",reference);
place.put("place_id", place_id);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}

How to show multiple marks on google map v2

I want to show multiple marks on google map v2 on run time.I have location table on remote server which contain all latitude and longitude.
I want to read latitude and longitude to show marker against each entry in location table but I don't know It give place one marker on google map.....First values in case of list and If use hashMap then give last value in database
Here is my code that am using to read and show marker on google map.Please help m and thanks in advance
public class MapActivity extends AppCompatActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
JSONArray jsonArray;
ArrayList<HashMap<String, String>> prodArrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> HashMap ;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(32.634723, 74.1601851)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
ActionStartsHere();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
ReadDriverLocation task1 = new ReadDriverLocation();
task1.execute(new String[]{"http://ahsan.comyr.com/ReadLocation.php"});
}
//This method call thread ofter 10 second
public void ActionStartsHere() {
CallBangroundClass();
}
public void CallBangroundClass() {
new CountDownTimer(11000, 30000) {
#Override
public void onTick(long millisUntilFinished) {
//Object of ReadActiveDriver Class extends with AsyncTask Class
}
#Override
public void onFinish() {
ActionStartsHere();
}
}.start();
}
///////////////////////////////////////////////////////////////////////////
private class ReadDriverLocation extends AsyncTask<String,Void,Boolean>
{
String text = "";
ArrayList<String> list;
ArrayList<String> list1;
ArrayList<String> list2;
#Override
protected Boolean doInBackground(String... urls) {
InputStream inputStream;
for(String url1: urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
inputStream = response.getEntity().getContent();
} catch (IOException e) {
Toast.makeText(MapActivity.this, e.toString(), Toast.LENGTH_LONG).show();
return false;
}
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine())!=null)
{
text += line +"\n";
}
} catch (IOException e) {
e.printStackTrace();
}
list = new ArrayList<String>();
list1 = new ArrayList<String>();
list2 = new ArrayList<String>();
HashMap = new HashMap<String, String>();
try {
jsonArray = new JSONArray(text);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String lati = jsonObject.getString("latitude");
String longLat = jsonObject.getString("longitude");
String Time = jsonObject.getString("time");
list.add(lati);
list1.add(longLat);
list2.add(Time);
//HashMap.put("Latitude", lati);
//HashMap.put("Longitude", longLat);
//HashMap.put("time", Time);
//prodArrayList.add(HashMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if(result == true)
{
for(int i=0; i<list.size(); i++)
{
Double latitude = Double.parseDouble(list.get(i));
Double longitude = Double.parseDouble(list1.get(i));
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(list2.get(i));
// GREEN color icon
mMap.addMarker(marker);
}
/*
for(int i=0; i<prodArrayList.size(); i++)
{
HashMap<String,String> hMap = prodArrayList.get(i);
Double latitude = Double.parseDouble(hMap.get("Latitude"));
Double longitude = Double.parseDouble(hMap.get("Longitude"));
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(hMap.get("time"));
// GREEN color icon
mMap.addMarker(marker);
}*/
}
else
{
Toast.makeText(MapActivity.this, "Error in Loading...",Toast.LENGTH_LONG).show();
}
}
}
}
When you use HashMap then you are getting last value because you are using same HashMap object in your for loop. According to HashMap definition,if you use same key then prior value for the key is dropped and replaced with the new one.
HashMap = new HashMap();// This hashMap is used entire for loop
try {
jsonArray = new JSONArray(text);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String lati = jsonObject.getString("latitude");
String longLat = jsonObject.getString("longitude");
String Time = jsonObject.getString("time");
// You use here duplicate key hence last value retained by hash map
HashMap.put("Latitude", lati);
HashMap.put("Longitude", longLat);
HashMap.put("time", Time);
prodArrayList.add(HashMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
In order to get right value from hashMap then create new instance for hashmap in for loop as follows :
try {
jsonArray = new JSONArray(text);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String lati = jsonObject.getString("latitude");
String longLat = jsonObject.getString("longitude");
String Time = jsonObject.getString("time");
HashMap = new HashMap<String, String>();
HashMap.put("Latitude", lati);
HashMap.put("Longitude", longLat);
HashMap.put("time", Time);
prodArrayList.add(HashMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
Set your marker as follows :
for(int i=0; i<prodArrayList.size(); i++)
{
HashMap<String,String> hMap = prodArrayList.get(i);
Double latitude = Double.parseDouble(hMap.get("Latitude"));
Double longitude = Double.parseDouble(hMap.get("Longitude"));
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(hMap.get("time"));
// GREEN color icon
mMap.addMarker(marker);
}

update value of holder textview in AsyncTask

I'm using google direction API to get the duration between my location and nearby places and it's working. But, I face problem in setting the duration value where the value is in onPostExecute.I tried to make duration global but it does not work. By the way, my textview is in ViewHolder class.
public class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
String distance = "";
String duration = "";
// Parsing the data in non-ui thread
#Override
public 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
public void onPostExecute(List<List<HashMap<String, String>>> result) {
/*ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();*/
if(result.size()<1){
Toast.makeText(context, "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
// 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);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
}
}
//holder.val.setText("value"+duration);
Toast.makeText(context,"Duration:"+duration ,Toast.LENGTH_LONG).show();
}

Get Specific data from json services while populating List

i need to populate a list view from data coming under the tag "group" from a JSON array "video". the coding under it is working fine if i remove if condition. Please help me guys. My boss is kicking my ass for this and my job is on the line. thanks in advance
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("video");
}
catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String countryName = "";
String flag="";
String language = "";
String capital = "";
String currencyCode = "";
String currencyName = "";
try {
countryName = jCountry.getString("Description");
flag = jCountry.getString("thumbnailUrl");
capital = jCountry.getString("title");
language=jCountry.getString("group");
Log.v("---","Country name: "+countryName+"Flag Url:"+flag+"Title"+capital);
if(language.equals("RokuTest-VideoGroup")){
country.put("country", countryName);
country.put("group", language);
country.put("flag", R.drawable.ic_launcher);
country.put("flag_path", flag);
country.put("details", capital);
Log.v("---","Country name: "+countryName+"Flag Url:"+flag+"Title"+capital);
}
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
Rohit.. Just manage the code in if and else block. It should work as you are saying removing if is working fine.
if(language.equals("RokuTest-VideoGroup")) {
// do somthing
}
else {
// do something
}

Android Google Map set country

I am new in developing with android google play sdk.
I want my map have a search function but it only specify on my country.
Let just say i live in Singapore, when i search a location, i want my engine only search on my country. How to set it ??
This is my Java Code
public class NearbyActivity extends FragmentActivity {
Button mBtnFind;
GoogleMap mMap;
EditText etPlace;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby);
// Getting reference to the find button
mBtnFind = (Button) findViewById(R.id.btn_show);
// Getting reference to the SupportMapFragment
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting reference to the Google Map
mMap = mapFragment.getMap();
// Getting reference to EditText
etPlace = (EditText) findViewById(R.id.et_place);
// Setting click event listener for the find button
mBtnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Getting the place entered
String location = etPlace.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://maps.googleapis.com/maps/api/geocode/json?";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String address = "address=" + location;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + address + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
});
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
CameraUpdate center=CameraUpdateFactory.newLatLng(myPosition);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
mMap.addCircle(new CircleOptions()
.center(myPosition)
.radius(450)
.strokeColor(Color.LTGRAY)
.fillColor(0x2000FFFF));
}
}
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 Places from Geocoding webservice */
private class DownloadTask 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){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Geocoding Places in non-ui thread */
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;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.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
mMap.clear();
for(int i=0;i<list.size();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("formatted_address");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker
markerOptions.title(name);
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And this is my GEOcodeJSON :
public class GeocodeJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount; i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String formatted_address = "-NA-";
String lat="";
String lng="";
try {
// Extracting formatted address, if available
if(!jPlace.isNull("formatted_address")){
formatted_address = jPlace.getString("formatted_address");
}
lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
place.put("formatted_address", formatted_address);
place.put("lat", lat);
place.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
You can set a bias for your query to prefer one region. Note that this will only prefer the specific region without excluding all other ones.
Based on your query you will have something like this:
https://maps.googleapis.com/maps/api/geocode/json?address=THEADDRESS&region=XX&sensor=true
XX is the ccTLD code of the region, e.g. sg for Singapore.

Categories

Resources