【问题标题】:How to show a specific location on map in android using Google Map Android API v2?如何使用 Google Map Android API v2 在 android 地图上显示特定位置?
【发布时间】:2013-06-07 11:38:50
【问题描述】:

我有这个问题。

我想在 android 的地图上显示一个特定的位置。就像用户在编辑文本中输入了印度一样,那么我如何在地图上显示印度。我基本上想知道如何获取任何位置的纬度和经度。

请帮忙

我的代码:

public class Map extends Activity{
private GoogleMap map;
private LatLng myLoc;

@SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    Intent i=getIntent();
    String loc=i.getStringExtra("loc");
    map  = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());  

    try {
        List<Address> addresses = geoCoder.getFromLocationName(
            loc, 5);

        if (addresses.size() > 0) {
            myLoc = new LatLng(
                    (int) (addresses.get(0).getLatitude() * 1E6), 
                    (int) (addresses.get(0).getLongitude() * 1E6));
            map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(myLoc, 14);
            map.animateCamera(update);
        }    
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

它不工作。请帮忙

【问题讨论】:

  • 有什么错误吗?这段代码的结果是什么?
  • @matreshkin 是的,NetworkOnMainThreadException;只用其他线程做阻塞操作
  • 您的代码适用于 Android API v2,因此我编辑了标题和标签。

标签: android google-maps android-intent google-maps-android-api-2 android-maps


【解决方案1】:

似乎Geocoder 功能被阻止并使用网络。因为 onCreate 在主线程上运行,you can get this error(in older versions of android). 因此,您必须创建 AsyncTask 并将地理编码器的函数移动到 AsyncTask.doInBackground()。

之后,在 AsyncTask.onPostExecute() 中,您应该使用谷歌地图执行其他操作。 (在这种情况下它会在主线程上,它必须是)

【讨论】:

    【解决方案2】:

    使用

    map.setMyLocationEnabled(true);
    

    地图上会出现一个蓝色圆圈。它将显示当前位置。

    【讨论】:

      【解决方案3】:

      当你从edittext中选择印度时调用这个函数:

      public void showSelectedCountry(String countryName) {
      
          if (countryName.equals("India")) {
      
              LatLngBounds boundsIndia = new LatLngBounds(new LatLng(23.63936, 68.14712), new LatLng(28.20453, 97.34466));
              int padding = 0; // offset from edges of the map in pixels
              CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(boundsIndia, padding);
              mMap.animateCamera(cameraUpdate);
      
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多