2015-06-02 25 views
-3

我想查找我的位置座標(緯度,經度)並在谷歌地圖上顯示它。我如何才能做到這一點,如果我只知道Java? 我在哪裏可以找到編碼材料或任何教程?如何使用java代碼來查找我的位置?

+0

找出你可以使用谷歌的地理編碼API的地址的座標。看看這個[教程](https://developers.google.com/maps/documentation/geocoding/) –

+0

你可以通過http://www.codeproject.com/Articles/209616/A-simple-GPS-基於應用到記錄電流-1 – Prashant

回答

1

下面的代碼可能對你有幫助...

package com.hello; 

import java.net.URLConnection; 
import java.net.URLEncoder; 
import java.util.List; 
import java.io.InputStream; 
import org.apache.commons.io.IOUtils; 
import org.codehaus.jackson.map.ObjectMapper; 

public class Test { 

private static final String URL = "http://maps.googleapis.com/maps/api/geocode/json"; 
public GoogleResponse convertToLatLong(String fullAddress) throws IOException { 
URL url = new URL(URL + "?address="+ URLEncoder.encode(fullAddress, "UTF-8") + "&sensor=false"); 
// Open the Connection 
URLConnection conn = url.openConnection(); 
InputStream in = conn.getInputStream() ; 
ObjectMapper mapper = new ObjectMapper(); 
GoogleResponse response = (GoogleResponse)mapper.readValue(in,GoogleResponse.class); 
in.close(); 
return response; 
} 

public GoogleResponse convertFromLatLong(String latlongString) throws IOException { 

URL url = new URL(URL + "?latlng="+ URLEncoder.encode(latlongString, "UTF-8") + "&sensor=false"); 
// Open the Connection 
URLConnection conn = url.openConnection(); 
InputStream in = conn.getInputStream() ; 
ObjectMapper mapper = new ObjectMapper(); 
GoogleResponse response = (GoogleResponse)mapper.readValue(in,GoogleResponse.class); 
in.close(); 
return response; 
} 

public static void main(String[] args) throws IOException { 
GoogleResponse res = new AddressConverter().convertToLatLong("Apollo Bunder,Mumbai ,Maharashtra, India"); 
if(res.getStatus().equals("OK")) 
{ 
    for(Result result : res.getResults()) 
    { 
    System.out.println("Lattitude of address is :" +result.getGeometry().getLocation().getLat()); 
    System.out.println("Longitude of address is :" + result.getGeometry().getLocation().getLng()); 
    System.out.println("Location is " + result.getGeometry().getLocation_type()); 
    } 
} 
else 
{ 
    System.out.println(res.getStatus()); 
} 

System.out.println("\n"); 
GoogleResponse res1 = new AddressConverter().convertFromLatLong("18.92038860,72.83013059999999"); 
if(res1.getStatus().equals("OK")) 
{ 
    for(Result result : res1.getResults()) 
    { 
    System.out.println("address is :" +result.getFormatted_address()); 
    } 
} 
else 
{ 
    System.out.println(res1.getStatus()); 
    } 
} 
}