我有一个google maps项​​目,您可以在其中输入一个地址,并且会显示一个标记,该地址,持续时间(乘车旅行)以及从用户位置到B点的距离。效果很好!

但是,我的问题是,每当我放置汽车无法访问的位置时,应用程序就会崩溃。我不是在寻找任何重要的东西,除了开车距离之外,我不需要任何其他东西,因此对于用户而言,告诉你不能在这里开车,对我来说很好。

我正在使用JSONParsing来解析UrlRequest之后的地址。腿,距离,持续时间,end_address,end-lat,end-lng是我从此文件中获取的值:

legs: [
{
    distance: {
        text: "547 km",
                value: 547015
    },
    duration: {
        text: "5 h 23 min",
                value: 19361
    },
    end_address: "Montreal, Quebec, Kanada",
            end_location: {
    lat: 45.5017123,
            lng: -73.5672184
},
    start_address: "Toronto, Ontario, Kanada",
            start_location: {
    lat: 43.6533096,
            lng: -79.3827656
},
    steps: [
    {
        distance: {
            text: "0,3 km",
                    value: 280
        },
        duration: {
            text: "1 min",
                    value: 66
        },
        end_location: {
            lat: 43.6557259,
                    lng: -79.3837337
        },
        html_instructions: "",
                polyline: {
        points: "e`miGhmocNs@Rm@N]JmA^KBcAZSFWHe@Nk@Pa@Le@L"
    },
        start_location: {
            lat: 43.6533096,
                    lng: -79.3827656
        },
        travel_mode: "DRIVING"
    },


所以我的问题是,对于这种方法要运行什么样的条件,是否有人有任何建议?

if(!=travel_mode: "DRIVING")
{
 Toast.makeText(MapsActivity.this, "You cannot drive there",
    Toast.LENGTH:SHORT).show();
}
else
{
   execute code;
}


获取travel_mode并以某种方式将其作为条件?先感谢您!

我的整个代码

主类,当您按下按钮时,地址将被转换

private void init() {
    searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            dataTransfer = new Object[2];
            url = getDirectionsUrl();
            GetDistances getDistances = new GetDistances();
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;
            getDistances.execute(dataTransfer);
            return false;
        }
    });


建立网址...

private String getDirectionsUrl()
{
    //WORKS
    //https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY"
    StringBuilder googleDirectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
    //Possible two textfields with origin being another textfield
    googleDirectionsUrl.append("origin="+myLat+","+myLng);
    googleDirectionsUrl.append("&destination="+searchText.getText().toString());
    googleDirectionsUrl.append("&key="+"API_KEY");

    return googleDirectionsUrl.toString();
}


发送要解析的网址...

public class DataParser {

private HashMap<String, String> getDuration(JSONArray googleDirectionsJson) {
    HashMap<String, String> googleDirectionsMap = new HashMap<>();
    String duration = "";
    String distance = "";
    String title = "";

    Log.d("json response", googleDirectionsJson.toString());
    try {
        duration = googleDirectionsJson.getJSONObject(0).getJSONObject("duration").getString("text");
        distance = googleDirectionsJson.getJSONObject(0).getJSONObject("distance").getString("text");
        title = googleDirectionsJson.getJSONObject(0).getString("end_address");

        googleDirectionsMap.put("duration", duration);
        googleDirectionsMap.put("distance", distance);
        googleDirectionsMap.put("end_address", title);

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

public HashMap<String, String> parseDirections(String jsonData) {
    JSONArray jsonArray = null;
    JSONObject jsonObject;

    try {
        jsonObject = new JSONObject(jsonData);
        jsonArray = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return getDuration(jsonArray);
}

private HashMap<String, Double> getLatLng(JSONArray googleLatLngJson) {
    HashMap<String, Double> googleLatLngMap = new HashMap<>();
    Double latitude = 0.0;
    Double longitude = 0.0;

    try {
        latitude = googleLatLngJson.getJSONObject(0).getJSONObject("end_location").getDouble("lat");
        longitude = googleLatLngJson.getJSONObject(0).getJSONObject("end_location").getDouble("lng");

        googleLatLngMap.put("lat", latitude);
        googleLatLngMap.put("lng", longitude);
        Log.d("json response", googleLatLngMap.toString());

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

public HashMap<String, Double> parseLatLng(String jsonData) {
    JSONArray jsonArray = null;
    JSONObject jsonObject;

    try {
        jsonObject = new JSONObject(jsonData);
        jsonArray = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return getLatLng(jsonArray);
}


}

从JSONparsed哈希图中获取值,然后将其放入新的哈希图中,以添加带有其值的标记

public class GetDistances extends AsyncTask<Object, String, String>{

GoogleMap mMap;
String url;
String googleDirectionsData;
String duration, distance;
Double latitude, longitude;
LatLng latLng;
String title;

@Override
protected String doInBackground(Object... objects) {
   mMap = (GoogleMap)objects[0];
   url = (String)objects[1];

   HttpHandler httpHandler = new HttpHandler();
   try
   {
       googleDirectionsData = httpHandler.readUrl(url);
   }
   catch(IOException e)
   {
       e.printStackTrace();
   }
   return googleDirectionsData;
}

@Override
protected void onPostExecute(String s)
{
    DataParser parser = new DataParser();

    HashMap<String, String> directionsList = null;
    directionsList = parser.parseDirections(s);
    duration = directionsList.get("duration");
    distance = directionsList.get("distance");
    title = directionsList.get("end_address");


    HashMap<String, Double> positionList = null;
    positionList = parser.parseLatLng(s);
    latitude = positionList.get("lat");
    longitude = positionList.get("lng");
    latLng = (new LatLng(latitude, longitude));

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
    MarkerOptions markerOptions = new MarkerOptions()
            .position(latLng)
            .draggable(true)
            .title(title);
    markerOptions.snippet("Distance: " + distance + ", " + "Duration: " + duration);

    mMap.addMarker(markerOptions);
}
}


“ API_KEY”-是我的实际密钥,只是试图将其保密。

解决了
 我只是在onPostExecute方法中进行了尝试,它解决了崩溃问题。

public class GetDestination extends AsyncTask<Object, String, String>{

GoogleMap mMap;
String url;
String googleDirectionsData;
String duration, distance;
Double latitude, longitude;
LatLng latLng;
String title;

private static Context context;
public GetDestination(Context c){
    context = c;
}

public static void showToast(){
    Toast.makeText(context, "You can't drive through the oceans!", Toast.LENGTH_LONG).show();
}

@Override
protected String doInBackground(Object... objects) {
   mMap = (GoogleMap)objects[0];
   url = (String)objects[1];

   HttpHandler httpHandler = new HttpHandler();
   try
   {
       googleDirectionsData = httpHandler.readUrl(url);
   }
   catch(IOException e)
   {
       e.printStackTrace();
   }
   return googleDirectionsData;
}

@Override
protected void onPostExecute(String s)
{
    try {
        DataParser parser = new DataParser();

        HashMap<String, String> directionsList = null;
        directionsList = parser.parseDirections(s);
        duration = directionsList.get("duration");
        distance = directionsList.get("distance");
        title = directionsList.get("start_address");


        HashMap<String, Double> positionList = null;
        positionList = parser.parseLatLng(s);
        latitude = positionList.get("lat");
        longitude = positionList.get("lng");

        latLng = (new LatLng(latitude, longitude));

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .draggable(true)
                .title(title);
        markerOptions.snippet("Distance: " + distance + ", " + "Duration: " + duration);

        mMap.addMarker(markerOptions);
    }
    catch (Exception e)
    {
        showToast();
        e.printStackTrace();
    }
}
}


确保在Mainactivity类中传递上下文,

searchText1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                dataTransfer = new Object[2];
                url = getDirectionsUrl();
                GetDestination getDestination = new GetDestination(MapsActivity.this);
                dataTransfer[0] = mMap;
                dataTransfer[1] = url;
                getDestination.execute(dataTransfer);
                return false;
        }
    });

最佳答案

您自己解决了这个问题真是太好了。恭喜。

但是更好的方法是在响应中放入log并检查两个responses之间的差异,即drivable and not drivable

这样,您可以读取确切的响应,并根据响应可以向用户显示不同的消息。

当然,try, catch可以在那里处理任何类型的异常。

希望这可以帮助。

关于android - 当您无法开车前往某个位置时,Google Maps崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49943246/

10-11 00:19