2014-12-19 117 views
0

我正在創建瑞典一些城市的地圖,並希望爲其添加一些功能。我想顯示城市名稱和距離地圖中心最近的城市的公里距離,我在佈局XML文件中放置了一個穿過ImageView的十字線。有沒有適當的方法來完成這個?Toast名稱和距離地圖中心最近的城市的距離

這是我目前使用創建我的地圖,並把我的城市標誌代碼:

public class MyMap extends Activity implements OnMapReadyCallback 
{ 
    public final Context context = this; 
    private String fileString = ""; 
    private String coordsFileName = "coords"; 
    private GoogleMap myMap = null; 
    private LatLngBounds bounds = null; 

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

    // Gets the map fragment from the xml file 
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 

    // Load strings from file 
    fileString = ReadFromFile(coordsFileName); 
} 

@Override 
public void onMapReady(GoogleMap map) 
{ 
    myMap = map; 
    List<Marker> markers = new ArrayList<Marker>(); 

    String[] locations = fileString.split(";"); 
    for (String location : locations) 
    { 
     try 
     { 
      String[] cityLatLng = location.split(":|,"); 
      String cityName = cityLatLng[0]; 
      Double lat = Double.parseDouble(cityLatLng[1]); 
      Double lng = Double.parseDouble(cityLatLng[2]); 
      LatLng cityPos = new LatLng(lat, lng); 

      // Create marker 
      Marker marker = myMap.addMarker(new MarkerOptions() 
      .position(cityPos) 
      .title(cityName)); 

      // Add new marker to array of markers 
      markers.add(marker); 
     } 
     catch(Exception e) 
     { 
      System.out.println("Error 3: " + e.getMessage()); 
     } 
    } 

    // Move the camera to show all markers 
    LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
    for (Marker marker : markers) 
    { 
     builder.include(marker.getPosition()); 
    } 
    bounds = builder.build(); 

    myMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() 
    { 
     @Override 
     public void onMapLoaded() 
     { 
      // Pixel offset from edge of map 
      int padding = 30; 

      // Move the camera 
      myMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding)); 
     } 
    }); 
} 

}

這是我的佈局xml文件:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<fragment 
    android:id="@+id/map" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:name="com.google.android.gms.maps.MapFragment"/> 
<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/ic_action_locate" 
    android:layout_gravity="center_vertical" 
    android:layout_centerInParent="true" 
    android:contentDescription="@string/crosshairs"/> 
</RelativeLayout> 

回答

0

我實際上設法使用Location對象和GoogleMap.setOnCameraChangeListener()來重新計算每次用戶導航地圖。以下是我設法實現的代碼。

 myMap.setOnCameraChangeListener(new OnCameraChangeListener() 
     { 
      @SuppressLint("DefaultLocale") @Override 
      public void onCameraChange(CameraPosition position) 
      { 
       // Get the latlng of the map center 
       LatLng mapCenter = myMap.getCameraPosition().target; 

       // Create a centerlocation based on the map's latlng 
       Location centerLocation = new Location("CenterLocation"); 
       centerLocation.setLatitude(mapCenter.latitude); 
       centerLocation.setLongitude(mapCenter.longitude); 

       // Location for storage of the city closest to the map 
       Location closestCity = new Location("ClosestCity"); 
       float distance = 0; 

       for (City city : cities) 
       { 
        Location cityLocation = new Location(city.getCityName()); 
        cityLocation.setLatitude(city.getLatitude()); 
        cityLocation.setLongitude(city.getLongitude()); 

        float currentCityDistance = cityLocation.distanceTo(centerLocation); 

        if(distance == 0) 
        { 
         distance = currentCityDistance; 
         closestCity = cityLocation; 
        } 

        if(currentCityDistance < distance) 
        { 
         distance = currentCityDistance; 
         closestCity = cityLocation; 
        } 
       } 

       // Convert from meters to kilometers 
       float distanceKm = distance/1000; 
       String kilometersString = String.format("%.2f", distanceKm); 

       // Present a toast with information 
       Toast.makeText(getBaseContext(), "Distance to " + closestCity.getProvider() + ": " + kilometersString + " km", Toast.LENGTH_SHORT).show(); 
      } 
     }); 
1

可能的解決方案之一是首先使用

map.getCenter(); 
找到地圖的中心座標

這將返回latlang對象。然後,您可以使用Google Distance Matrix API比較中心與每個位置標記(代表城市)的距離,使用minDist()方法找出最小值,並以最小距離返回標記的座標(這是城市)

希望能幫助!!!

+0

謝謝!聽起來很不錯,我會試試看! – Lemonmuncher 2014-12-20 08:59:02