2014-01-02 3 views
0

Я новичок в разработке с Android-игрой sdk. Я хочу, чтобы у моей карты была функция поиска, но она указана только в моей стране. Позвольте мне сказать, что я живу в Сингапуре, когда я ищу место, я хочу, чтобы мой двигатель выполнял поиск только в моей стране. Как это установить?Android Google Map set country

Это мой Java код

public class NearbyActivity extends FragmentActivity { 

Button mBtnFind; 
GoogleMap mMap; 
EditText etPlace; 
LatLng myPosition; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.nearby); 

    // Getting reference to the find button 
    mBtnFind = (Button) findViewById(R.id.btn_show); 

    // Getting reference to the SupportMapFragment 
    SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map); 

    // Getting reference to the Google Map 
    mMap = mapFragment.getMap(); 

    // Getting reference to EditText 
    etPlace = (EditText) findViewById(R.id.et_place); 

    // Setting click event listener for the find button 
    mBtnFind.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // Getting the place entered 
      String location = etPlace.getText().toString(); 

      if(location==null || location.equals("")){ 
       Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show(); 
       return; 
      } 

      String url = "https://maps.googleapis.com/maps/api/geocode/json?"; 

      try { 
       // encoding special characters like space in the user input place 
       location = URLEncoder.encode(location, "utf-8"); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 

      String address = "address=" + location; 

      String sensor = "sensor=false"; 

      // url , from where the geocoding data is fetched 
      url = url + address + "&" + sensor; 

      // Instantiating DownloadTask to get places from Google Geocoding service 
      // in a non-ui thread 
      DownloadTask downloadTask = new DownloadTask(); 

      // Start downloading the geocoding places 
      downloadTask.execute(url); 
     } 
    }); 
    mMap.setMyLocationEnabled(true); 
    mMap.getUiSettings().setCompassEnabled(true); 
    mMap.getUiSettings().setMyLocationButtonEnabled(true); 
    mMap.getUiSettings().setRotateGesturesEnabled(true); 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

    // Creating a criteria object to retrieve provider 
    Criteria criteria = new Criteria(); 

    // Getting the name of the best provider 
    String provider = locationManager.getBestProvider(criteria, true); 

    // Getting Current Location 
    Location location = locationManager.getLastKnownLocation(provider); 


    if(location!=null){ 
     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 
     LatLng latLng = new LatLng(latitude, longitude); 
     myPosition = new LatLng(latitude, longitude); 
     CameraUpdate center=CameraUpdateFactory.newLatLng(myPosition); 
     CameraUpdate zoom=CameraUpdateFactory.zoomTo(15); 
     mMap.moveCamera(center); 
     mMap.animateCamera(zoom); 
     mMap.addCircle(new CircleOptions() 
      .center(myPosition) 
      .radius(450) 
      .strokeColor(Color.LTGRAY) 
      .fillColor(0x2000FFFF)); 
    } 

} 

private String downloadUrl(String strUrl) throws IOException{ 
    String data = ""; 
    InputStream iStream = null; 
    HttpURLConnection urlConnection = null; 
    try{ 
     URL url = new URL(strUrl); 
     // Creating an http connection to communicate with url 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     // Connecting to url 
     urlConnection.connect(); 

     // Reading data from url 
     iStream = urlConnection.getInputStream(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

     StringBuffer sb = new StringBuffer(); 

     String line = ""; 
     while((line = br.readLine()) != null){ 
      sb.append(line); 
     } 

     data = sb.toString(); 
     br.close(); 

    }catch(Exception e){ 
     Log.d("Exception while downloading url", e.toString()); 
    }finally{ 
     iStream.close(); 
     urlConnection.disconnect(); 
    } 

    return data; 
} 
/** A class, to download Places from Geocoding webservice */ 
private class DownloadTask extends AsyncTask<String, Integer, String>{ 

    String data = null; 

    // Invoked by execute() method of this object 
    @Override 
    protected String doInBackground(String... url) { 
     try{ 
      data = downloadUrl(url[0]); 
     }catch(Exception e){ 
      Log.d("Background Task",e.toString()); 
     } 
     return data; 
    } 

    // Executed after the complete execution of doInBackground() method 
    @Override 
    protected void onPostExecute(String result){ 

     // Instantiating ParserTask which parses the json data from Geocoding webservice 
     // in a non-ui thread 
     ParserTask parserTask = new ParserTask(); 

     // Start parsing the places in JSON format 
     // Invokes the "doInBackground()" method of the class ParseTask 
     parserTask.execute(result); 
    } 
} 

/** A class to parse the Geocoding Places in non-ui thread */ 
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{ 

    JSONObject jObject; 

    // Invoked by execute() method of this object 
    @Override 
    protected List<HashMap<String,String>> doInBackground(String... jsonData) { 

     List<HashMap<String, String>> places = null; 
     GeocodeJSONParser parser = new GeocodeJSONParser(); 

     try{ 
      jObject = new JSONObject(jsonData[0]); 

      /** Getting the parsed data as a an ArrayList */ 
      places = parser.parse(jObject); 

     }catch(Exception e){ 
      Log.d("Exception",e.toString()); 
     } 
     return places; 
    } 

    // Executed after the complete execution of doInBackground() method 
    @Override 
    protected void onPostExecute(List<HashMap<String,String>> list){ 

     // Clears all the existing markers 
     mMap.clear(); 

     for(int i=0;i<list.size();i++){ 

      // Creating a marker 
      MarkerOptions markerOptions = new MarkerOptions(); 

      // Getting a place from the places list 
      HashMap<String, String> hmPlace = list.get(i); 

      // Getting latitude of the place 
      double lat = Double.parseDouble(hmPlace.get("lat")); 

      // Getting longitude of the place 
      double lng = Double.parseDouble(hmPlace.get("lng")); 

      // Getting name 
      String name = hmPlace.get("formatted_address"); 

      LatLng latLng = new LatLng(lat, lng); 

      // Setting the position for the marker 
      markerOptions.position(latLng); 

      // Setting the title for the marker 
      markerOptions.title(name); 

      // Placing a marker on the touched position 
      mMap.addMarker(markerOptions); 

      // Locate the first location 
      if(i==0) 
       mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
     } 
    } 
} 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
} 

И это мой GEOcodeJSON:

public class GeocodeJSONParser { 

/** Receives a JSONObject and returns a list */ 
public List<HashMap<String,String>> parse(JSONObject jObject){  

    JSONArray jPlaces = null; 
    try {   
     /** Retrieves all the elements in the 'places' array */ 
     jPlaces = jObject.getJSONArray("results"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    /** Invoking getPlaces with the array of json object 
    * where each json object represent a place 
    */ 
    return getPlaces(jPlaces); 
} 


private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){ 
    int placesCount = jPlaces.length(); 
    List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>(); 
    HashMap<String, String> place = null; 

    /** Taking each place, parses and adds to list object */ 
    for(int i=0; i<placesCount; i++){ 
     try { 
      /** Call getPlace with place JSON object to parse the place */ 
      place = getPlace((JSONObject)jPlaces.get(i)); 
      placesList.add(place); 

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

    return placesList; 
} 

/** Parsing the Place JSON object */ 
private HashMap<String, String> getPlace(JSONObject jPlace){ 

    HashMap<String, String> place = new HashMap<String, String>(); 
    String formatted_address = "-NA-";  
    String lat=""; 
    String lng=""; 


    try { 
     // Extracting formatted address, if available 
     if(!jPlace.isNull("formatted_address")){ 
      formatted_address = jPlace.getString("formatted_address"); 
     }   

     lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat"); 
     lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");   


     place.put("formatted_address", formatted_address);   
     place.put("lat", lat); 
     place.put("lng", lng); 


    } catch (JSONException e) {   
     e.printStackTrace(); 
    }  
    return place; 
} 
} 
+0

Если вы используете google map api v2, вы можете установить видимую область. Пожалуйста, проверьте этот api. [https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/model/VisibleRegion] –

+0

Я использую google map api v2. Вы знаете, как его реализовать? –

ответ

0

Вы можете задать смещение для вашего запроса, чтобы предпочесть один регион. Обратите внимание, что это предпочтет только конкретный регион, не исключая всех остальных.

На основании вашего запроса вы будете иметь что-то вроде этого:

https://maps.googleapis.com/maps/api/geocode/json?address=THEADDRESS&region=XX&sensor=true 

XX является ccTLD код региона, например, sg для Сингапура.