blog-image

Using Google Maps API In Android App Development: Getting Geo Co-Ordinates

21 Nov. 12
5.34 K VIEWS

So now you will learn how to get Geo-coordinates from strings using Google’s maps API. Since you guys are kind of a newbie you have to learn a little something about the Google maps API and JSON objects. What we will be doing here is we will be accessing Google’s Maps API from our program. The API based on the String query we send will return a JSON object containing the results of our search in it. Pretty straight forward right?

So here is the lowdown on JSON. JSON  short for JavaScript Object Notation. It is a standard for information interchange that is easy for humans to read and easy for machines to parse. Hence the use in the Maps API. You can understand the conventions of JSON from the literature here.

So basically what we will be doing here is access the API, send a location to search for in a string, get the JSON object and make the program read and return the Latitude and Longitude from  it.

So now that you understand the mechanics of the program Lets dive in. Here is the code and we will dissect it later.

[sourcecode language=”java”]
public String SendLatLong(String Address)
{
String latlong = “”;
try
{
String readadress = readTwitterFeed(“http://maps.googleapis.com/maps/api/geocode/json?address=”+ Address.replaceAll(” “, “%20”) + “&sensor=false”);
JSONObject jsonObject = new JSONObject(readadress).getJSONArray(“results”).getJSONObject(0).getJSONObject(“geometry”).getJSONObject(“location”);
String eventLat = jsonObject.getString(“lat”);
String eventLng = jsonObject.getString(“lng”);
latlong = eventLat + “,” + eventLng;
}
catch (Exception e)
{
}
return latlong;
}

public String readTwitterFeed(String url)
{
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return builder.toString();
}
[/sourcecode]

Explanation of program:

The main work being done here is done by the SendLatLong function which is the main function and will be returning the latitude and longitude. Observe that it accepts an argument  “Address” which is the name of the location of which we want the latitude and longitude.

Now notice the String variable “latlong”. We will be using this string to return the coordinates that we will be obtaining.

Address(Request) Parsing

Now the core logic of the program is encapsulated in the try-catch block of the function. Let me break this down a notch further. Lets look at the bit of code:

[sourcecode language=”java”]
String readadress = readTwitterFeed(“http://maps.googleapis.com/maps/api/geocode/json?address=”+ Address.replaceAll(” “, “%20”) + “&sensor=false”);
[/sourcecode]

We have another string readadress that is getting  a string returned by a function  readTwitterFeed. What I want you to closely at is the argument being passed into it. You will notice that our original argument “Address” is concatenated to into a URL. What is happening here is that we are passing queries into Google’s Maps API through a query string. That is why we have to replace the spaces with “%20” so that the search engine can parse it by applying the function replaceAll on Address.

Not getting it? Ok let us get the JSON file for Taj Mahal. As you can see the value for the “Address” is “Taj Mahal”. We will now add it to the URL so we will have to remove the space between  Taj and Mahal and put %20 to allow the search engine program to parse it. So our URL will be:

http://maps.googleapis.com/maps/api/geocode/json?address=Taj%20Mahal&sensor=false

Now copy the URL above and paste it into your browser to fetch the JSON object. Give it a shot. Your browser will directly open the JSON file returned by the API.

URL parsing

We do not need to delve deeper into the readTwitterFeed function but you should understand why it is there. What it does is it reads in a string and returns a stringBuilder object. What this does is preventing the data from the JSON file from getting read into the URL which is undesirable because it would result in complicated string parsing methods.

Now moving on we now have a static web address pointing to a JSON resource that is stored in the string readadress. We read the same address into a JSON object as shown below:

[sourcecode language=”java”]
JSONObject jsonObject = new JSONObject(readadress).getJSONArray(“results”).getJSONObject(0).getJSONObject(“geometry”).getJSONObject(“location”);
[/sourcecode]

The data that we have stored in the JSON object is the latitude and longitude of our searched location. This data we store into separate strings with the following:

[sourcecode language=”java”]
String eventLat = jsonObject.getString(“lat”);
String eventLng = jsonObject.getString(“lng”);
latlong = eventLat + “,” + eventLng;
[/sourcecode]

The separate strings are concatenated into latlong which is returned by our primary function.

The things you have seen up till now should suffice if you plan to just get the Geo-coordinates . If you want to delve deeper into the details or want to learn how to get other geographic data you will have to read the next post. Till then you can play around with this code and understand it properly. So now you have got a grip on using Google Maps API In Android Application Development. we have used this api in couple of android applications you can check all those android applications on Google store here..

Blog A directory of wonderful things

The demand for storage capacity in Mobile Application is ever increasing with each new resolution for device being introduced. The issue becomes more apparent in case of Game application, one …

Internal Storage is one of the common issues right now for iPhone users. The most annoying notification ‘Storage Almost Full: you can manage your storage in Settings’ on your iPhone.Full …

In this booming rise of smartphones all over the world has resulted in a surge in the number of apps that people are using. Google houses 2.2 million apps in …

LetsNurture wishes you all a very happy new year. We hope you already have planned your new year resolutions. At LetsNurture, our employees surely have taken some innovative resolutions. We, …

According to the Green Car report, 1.2 Billion vehicles are on world’s roads now, making 2 billion by 2035. With these many vehicles to maintain, the service stations have to …

It is well said that to reach the bright success, one needs to climb every step carefully without taking a short-cut. Short-cut always leads to failure at one or other …

Who would not want to save money? People are always looking for products or solutions that can help them effectively spend their money. Well, for the businesses, it is an …

The development of iOS10 has made the iPhone users happy by introducing interactive features. ‘Express yourself in bold new ways in Messages. Relive memories like never before in Photos. And …

When you have an unplanned dine-out and you don’t get a table at your favorite restaurant, that’s when you seek help of your friend (smartphone) to know where else to …

Android being an open source OS is never considered good on part of security concerns. It is so because it relies heavily on its vendors to push updates which might …

Know Google IO Google IO is known for its highly technical, in-depth sessions focused on building the web, mobile, and enterprise applications with Google. It is believed that IO in …

Should I get my app developed using native or hybrid technology? If you are in IT industry, you would have come across this question more often. Non-technical entrepreneurs go crazy …

In my last month’s LinkedIn post  USER RETENTION- A Checklist to ensure Consistent Growth, I had tried to highlight strategies and check list items, for ensuring consistent growth in new …

In the future, a single device for all of our home entertainment consumption will become the norm. As global adoption of smart TV grows rapidly, a tipping point in the …

Let me put things in a simple and straight way. I don’t need to explain about the universal presence of the mobile phones and the way new mobile-related technology is …

Electricity is the most useful invention, at the same time is very hazardous too. It’s not everybody’s cup of tea to handle those colourful wires which make our lives entertaining! …

Google Cast, is a technology that allows us to cast our favorite entertainment and application from our phones, tablets or laptops right to our TV or speakers. Chromecast has changed …

What do you do when you are at some place, a lesser known one, but the curious soul in you want answers for all everything around even when you don’t …

Parents need to do everything possible to verify their kids are healthy and secure from preventable sicknesses. Immunization is the most ideal approach to do that. Vaccination is critical for …

200 Beacons will be straightened across UK’s major airport to render well-timed and targeted notification to their passengers on the mobile devices. Mobile Payment Technologies programmer Proxama features joined together …

CONTACT US

Have an !dea or need help with your current business?

For immediate assistance in sales or support, please call us on:

+1-631-954-6922

loading...