Get Latitude and Longitude with Geocoder and Android Google Maps API V2

get latitude and longitude with geocoder and android Google Maps API v2

Try this solution using this example url:

http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false

which returns data in json format with lat/lng of address.

private class DataLongOperationAsynchTask extends AsyncTask<String, Void, String[]> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}

@Override
protected String[] doInBackground(String... params) {
String response;
try {
response = getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false");
Log.d("response",""+response);
return new String[]{response};
} catch (Exception e) {
return new String[]{"error"};
}
}

@Override
protected void onPostExecute(String... result) {
try {
JSONObject jsonObject = new JSONObject(result[0]);

double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");

double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");

Log.d("latitude", "" + lat);
Log.d("longitude", "" + lng);
} catch (JSONException e) {
e.printStackTrace();
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

public String getLatLongByURL(String requestURL) {
URL url;
String response = "";
try {
url = new URL(requestURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setDoOutput(true);
int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}

} catch (Exception e) {
e.printStackTrace();
}
return response;
}

Hope this will helps you.

How to get address from latitude and longitude android google map v2

Use the following code snippet:

try { 
Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextfieldname.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}

reference :
https://mobiforge.com/design-development/using-google-maps-android

Does Geocoder actually work with google map api v2?

googleMap variable is null because you never assign the variable.

Add onMapReady:

this.googleMap = googleMap;

How to get geographical coordinates in google maps API V2 android using an string address?

You can use the Geocoder class to do a look-up of the addresses you have, and then populate the map with Markers using the LanLng objects that are returned.

Note that the Geocoder class will not be able to geocode every address, but it will be successful for most of them if they are in the correct format.

Taking code from this question as a guide, I just got this simple example working.

I created a custom class that stores location name, location address, and a LatLng object to store the lat/lon.

For this simple example, I just used three addresses.

Here is the full class code:

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MapsActivity extends AppCompatActivity {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}

@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}

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();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}

private void setUpMap() {
mMap.setMyLocationEnabled(true);

List<CustomLocation> custLocs = new ArrayList<CustomLocation>();

//Testing with three addresses
custLocs.add(new CustomLocation("location 1", "100 market street san francisco ca"));
custLocs.add(new CustomLocation("location 2", "200 market street san francisco ca"));
custLocs.add(new CustomLocation("location 3", "300 market street san francisco ca"));

//set the location for each item in the list
for (CustomLocation custLoc : custLocs){
custLoc.setLocation(getSingleLocationFromAddress(custLoc.address));
}

//draw the Marker for each item in the list
for (CustomLocation custLoc : custLocs){
mMap.addMarker(new MarkerOptions().position(custLoc.latLng)
.title(custLoc.name).icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
}

//method to do a lookup on the address
public LatLng getSingleLocationFromAddress(String strAddress)
{
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address = null;
Address location = null;
LatLng temp = null;
String strAddresNew = strAddress.replace(",", " ");
try
{
address = coder.getFromLocationName(strAddresNew, 1);
if (!address.isEmpty())
{
location = address.get(0);
location.getLatitude();
location.getLongitude();
temp = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("Latlng : ", temp + "");
}
} catch (IOException e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return temp;
}

//class to hold the name and address and location
public static class CustomLocation{

public String name;
public String address;
public LatLng latLng;
public CustomLocation(String n, String a){
name = n;
address = a;
}
public void setLocation(LatLng ll){
latLng = ll;
}
}
}

Result:

Sample Image

How to get complete address from latitude and longitude?

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

For more info of available details, Look at Android-Location-Address

Android Google Maps Api V2, getting the coordinates for the current map center

but I can't get the lat/long from the CameraPosition object

The target public data member on a CameraPosition is a LatLng of the map center, based upon my reading of the docs.

How can I find the latitude and longitude from address?

public GeoPoint getLocationFromAddress(String strAddress) {

Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;

try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();

p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
(double) (location.getLongitude() * 1E6));

return p1;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

strAddress is a string containing the address. The address variable holds the converted addresses.



Related Topics



Leave a reply



Submit