Hausfer
Hausfer

Reputation: 37

Trying to get LatLng from an address or location in android

Ok next problem.

I am trying to take an imputed address or location and output a LatLng for storage. This is what I have so far based on How can I find the latitude and longitude from address?, third answer down.

import java.util.List;

import com.google.android.gms.maps.model.LatLng;


import android.app.Fragment;
import android.location.Address;
import android.location.Geocoder;

public class Mapping extends Fragment
{


    public LatLng getLocationFromAddress(String _address) {

        Geocoder coder = new Geocoder(getActivity());
        List<Address> address;
        LatLng p1 = null;

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

            p1 = new LatLng(location.getLatitude(), location.getLongitude() );

        } catch (Exception ex) {

            ex.printStackTrace();
        }

        return p1;

I try to call it in another class like this.

 make.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //String _name = (String) txtName.getText().toString();
                //String _address = (String) txtAddress.getText().toString();
                String _name = "Some Name"; //Just to pass some information
                String _address = "New York";
                contact.setName(_name);
                contact.setAddress(_address);

                // Should populate lladdress with a LatLng
                LatLng lladdress = mapping.getLocationFromAddress(_address);
                contact.setLatLng(lladdress);
           }
});

All the code up to // Should populate lladdress with a LatLng works but if I add this part in my app stops working. I have used Toast in the past to test the code but I don't know how to test this and I try and debug and don't see anything useful. Any ideas of what is wrong with my code?

Update: Thanks @bjiang for your code. I decided to change it so output a double2 and return it so I can store it in a database or use it how I need later.

public class Mapping extends Fragment
{
	
	//String[] happy = new String[2];
	
	protected double[] getLatLng(Context context, String address/*, boolean setDestination*/) {
        String uri = "http://maps.google.com/maps/api/geocode/json?address="
                + address + "&sensor=false";
        
		Message.message(context , ""+uri);

        HttpGet httpGet = new HttpGet(uri);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();

            InputStream stream = entity.getContent();

            int byteData;
            while ((byteData = stream.read()) != -1) {
                stringBuilder.append((char) byteData);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        double[] _latlng = new double[2];

        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
            _latlng[1] = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");
            _latlng[0] = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        
		return _latlng;
It is still failing and from what I am reading from the exception it is throwing "android.os.NetworkOnMainThreadException" according to this post I need to run it as an AsyncTask but I am not sure if this is true or how to do it. does my code look right and does anyone have any other ideas?

Here is some of the log:

03-15 12:30:05.803: E/AndroidRuntime(17863): FATAL EXCEPTION: main

03-15 12:30:05.803: E/AndroidRuntime(17863): Process: edu.ecpi.myappv3, PID: 17863

03-15 12:30:05.803: E/AndroidRuntime(17863): android.os.NetworkOnMainThreadException

03-15 12:30:05.803: E/AndroidRuntime(17863): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)

03-15 12:30:05.803: E/AndroidRuntime(17863): at java.net.InetAddress.lookupHostByName(InetAddress.java:418)

03-15 12:30:05.803: E/AndroidRuntime(17863): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)

03-15 12:30:05.803: E/AndroidRuntime(17863): at java.net.InetAddress.getAllByName(InetAddress.java:215)

03-15 12:30:05.803: E/AndroidRuntime(17863): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:172)

03-15 12:30:05.803: E/AndroidRuntime(17863): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)

Upvotes: 1

Views: 2511

Answers (1)

bjiang
bjiang

Reputation: 6078

I used following method to get the LatLng form an address:

protected void getLatLng(String address) {
        String uri = "http://maps.google.com/maps/api/geocode/json?address="
                + address + "&sensor=false";

        HttpGet httpGet = new HttpGet(uri);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();

            InputStream stream = entity.getContent();

            int byteData;
            while ((byteData = stream.read()) != -1) {
                stringBuilder.append((char) byteData);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        double lat = 0.0, lng = 0.0;

        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
            lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");
            lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

        } catch (JSONException e) {
            e.printStackTrace();
        }
}

You need put it into AsyncTask to doInBackground to fetch the data form Internet.

For whole project source code, please refer to my Github here. This demonstrate get LatLng form the address and also can set a marker to there.

enter image description here

Upvotes: 2

Related Questions