试图从android中的地址或位置获取LatLng

时间:2015-03-13 21:43:40

标签: android google-maps google-geocoder

好的下一个问题。

我正在尝试获取推算的地址或位置,并输出LatLng进行存储。 这是我到目前为止基于How can I find the latitude and longitude from address?,第三个回答。

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;

我尝试在另一个类中调用它。

 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);
           }
});

所有代码// Should populate lladdress with a LatLng都有效,但如果我在我的应用中添加此部分则停止工作。我过去使用Toast来测试代码,但我不知道如何测试这个,我尝试调试,看不到任何有用的东西。我的代码有什么问题吗?

更新: 感谢@bjiang为您的代码。我决定改变它,所以输出一个双2并返回它,这样我就可以将它存储在数据库中,或者以后我需要它。

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;
它仍然失败,从我从异常中读取它根据this帖子抛出“android.os.NetworkOnMainThreadException”我需要将其作为AsyncTask运行但是我不确定这是真的还是如何去做吧。我的代码看起来是否正确,是否有人有任何其他想法?

以下是一些日志:

03-15 12:30:05.803:E / AndroidRuntime(17863):致命异常:主

03-15 12:30:05.803:E / AndroidRuntime(17863):进程: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):在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)

1 个答案:

答案 0 :(得分:2)

我使用以下方法获取LatLng表单的地址:

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();
        }
}

您需要将其放入AsyncTaskdoInBackground以从互联网上获取数据。

有关整个项目源代码,请参阅我的Github here。这证明get LatLng form the address也可以set a marker to there

enter image description here