Hi Guys,
Today I am sharing the code about Google Map Android V2 and get the location on map by Geo-coding.
In this new version of Google Map Android there are many things are changed now.
1. For using this new feature you have installed the Google Play Service in your android SDK Manager. So need to installed. After installed this feature of sdk then automatically created the the google play service library project in your default folder (sdk\extras\google\google_play_services\libproject) .
Because we need to add this library project with our new android project with Google Map.
See the screen shot.
2. Now need to create the Google API key from Google API console.
Before create the new Google API key you need to switch on service of Google Map Android V2 from your Google Services. Please see the screen shot.
3. Now the next step need to create the SHA1 finger print by using the keytool and your project name.
So create the the Android name folder inside the C drive (C:\Android ) of your computer. And put the two file inside this folder. 1. debug.keystore 2. keytool.exe
4. In the next step you need to run the command on cmd to generate the SHA1 finger print key by using this keystore. So the command is :
keytool -list -v -keystore "C:\Android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
After run this command on cmd it will create the SHA1 finger key.
5. In this step you just copy thus SHA1 key from cmd and paste on the Google console of configure android key for API project with your android project package name.
After that your API key will show on your Google console. Now you can use that API key in your project.
6. Now need to import the Google-play -service_lib project in your eclipse. This project is stored inside the (sdk\extras\google\google_play_services\libproject).
7. So here we start the create the new project name "GoogleMapLocationAPIV2" and set the target with Google API and add the Google play service library project with this project. See the screen shot.
Today I am sharing the code about Google Map Android V2 and get the location on map by Geo-coding.
In this new version of Google Map Android there are many things are changed now.
1. For using this new feature you have installed the Google Play Service in your android SDK Manager. So need to installed. After installed this feature of sdk then automatically created the the google play service library project in your default folder (sdk\extras\google\google_play_services\libproject) .
Because we need to add this library project with our new android project with Google Map.
See the screen shot.
2. Now need to create the Google API key from Google API console.
Before create the new Google API key you need to switch on service of Google Map Android V2 from your Google Services. Please see the screen shot.
3. Now the next step need to create the SHA1 finger print by using the keytool and your project name.
So create the the Android name folder inside the C drive (C:\Android ) of your computer. And put the two file inside this folder. 1. debug.keystore 2. keytool.exe
4. In the next step you need to run the command on cmd to generate the SHA1 finger print key by using this keystore. So the command is :
keytool -list -v -keystore "C:\Android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
After run this command on cmd it will create the SHA1 finger key.
5. In this step you just copy thus SHA1 key from cmd and paste on the Google console of configure android key for API project with your android project package name.
After that your API key will show on your Google console. Now you can use that API key in your project.
6. Now need to import the Google-play -service_lib project in your eclipse. This project is stored inside the (sdk\extras\google\google_play_services\libproject).
7. So here we start the create the new project name "GoogleMapLocationAPIV2" and set the target with Google API and add the Google play service library project with this project. See the screen shot.
- Then right click of project select , Click �Android Tools -> Add Support Library �. In the new API it is already available then no need to add. Add only in below API.
activity_main.xml
MainActivity.java
package com.sunil.apiv2map.activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sunil.apiv2map.R;
public class MainActivity extends FragmentActivity {
Button mBtnFind;
GoogleMap mMap;
EditText etPlace;
private static final String TAG="MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG+"onCreate", "onCreate call");
// 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();
//MapFragment mapfragment =(MapFragment) getFragmentManager().findFragmentById(R.id.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
Log.v(TAG+"onClick", "onClick call");
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;
Log.v(TAG+"onClick", "url is: "+url);
// String modifiedURL= url.toString().replace(" ", "%20");
// 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);
}
});
}
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 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();
parserTask.execute(result);
}
}
class ParserTask extends AsyncTask>>{
JSONObject jObject;
@Override
protected List> doInBackground(String... jsonData) {
List> 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> list){
// Clears all the existing markers
mMap.clear();
for(int i=0;ihmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
String name = hmPlace.get("formatted_address");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name);
mMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
GeocodeJSONParser.java
package com.sunil.apiv2map.activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GeocodeJSONParser {
public List> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jPlaces);
}
private List> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List> placesList = new ArrayList >();
HashMapplace = null;
/** Taking each place, parses and adds to list object */
for(int i=0; igetPlace(JSONObject jPlace){
HashMapplace = new HashMap ();
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;
}
}
Now to add the manifest file the API key and Permissions . Please see the screen shot.
After run the project Google Map is loaded and find the location "btm layout Bangalore" screen looks like that:
And you can use the functionality of ZOOM when click on + button the location looks like that.
You can download the source code GoogleMapLocationAPIV2
Cheers Guys!!
Update Contact :
No Wa/Telepon (puat) : 085267792168
No Wa/Telepon (fajar) : 085369237896
Email : Fajarudinsidik@gmail.com
No Wa/Telepon (puat) : 085267792168
No Wa/Telepon (fajar) : 085369237896
Email: Fajarudinsidik@gmail.com
atau Kirimkan Private messanger melalui email dengan klik tombol order dibawah ini :