Getting the Distance between Locations using Google Maps API

Modifying my post on drawing directions in a MapView using Google's API, I have come up with a solution to get the distance between two locations. Considering the same example I modified getDirections() to the method given below which returns distance as a string in kms(or meters).
	public String getDistance(double lat1, double lon1, double lat2, double lon2) {
		String result_in_kms = "";
		String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
		String tag[] = {"text"};
		HttpResponse response = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost httpPost = new HttpPost(url);
			response = httpClient.execute(httpPost, localContext);
			InputStream is = response.getEntity().getContent();
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(is);
			if (doc != null) {
				NodeList nl;
				ArrayList args = new ArrayList();
				for (String s : tag) {
					nl = doc.getElementsByTagName(s);
					if (nl.getLength() > 0) {
						Node node = nl.item(nl.getLength() - 1);
						args.add(node.getTextContent());
					} else {
						args.add(" - ");
					}
				}
				result_in_kms = String.format("%s", args.get(0));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result_in_kms;
	}

By default the travel mode is set as driving; other modes are walking and bicycling. For instance to change mode we just need to append &mode=driving to to URL.

About these ads

2 thoughts on “Getting the Distance between Locations using Google Maps API

  1. Pingback: การหาระยะทางระหว่างจุดพิกัด 2 จุด « android4health

  2. Pingback: Android driving distance : Android Community - For Application Development

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s