2010-01-18 35 views
7

我正在編寫一個需要獲取當前地圖位置的應用程序。我的地圖文件可以自行工作,但我需要從另一個Activity獲取地址(請參閱下面的addressString)。我試過getAddress/setAddress(setters/getters)。他們不工作。他們總是返回「無地址」(默認)。獲取地圖或位置Android中的地址

這裏是我的代碼...

我怎樣才能使這個獨立的Java類???或從另一個活動獲取地址?

非常感謝。

此代碼自行工作。


import android.content.Context; 
import android.location.Address; 
import android.location.Criteria; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.widget.TextView; 

import java.io.IOException; 
import java.util.List; 
import java.util.Locale; 

public class GetMapAddress extends MapActivity { 

    MapController mapController; 

    MyPositionOverlay positionOverlay; 

    MapController mc; 

    GeoPoint p; 

    String addressString = "No address found"; 

    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.map); 

     MapView myMapView = (MapView) findViewById(R.id.myMapView); 
     mapController = myMapView.getController(); 

     // Configure the map display options 
     myMapView.setSatellite(true); 
     myMapView.setStreetView(true); 

     // Zoom in 
     mapController.setZoom(17); 

     myMapView.setBuiltInZoomControls(true); 

     // Add the MyPositionOverlay 
     positionOverlay = new MyPositionOverlay(); 
     List<Overlay> overlays = myMapView.getOverlays(); 
     overlays.add(positionOverlay); 

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     criteria.setAltitudeRequired(false); 
     criteria.setBearingRequired(false); 
     criteria.setCostAllowed(true); 
     criteria.setPowerRequirement(Criteria.POWER_LOW); 
     String provider = locationManager.getBestProvider(criteria, true); 

     Location location = locationManager.getLastKnownLocation(provider); 

     updateWithNewLocation(location); 

     locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); 

     mc = myMapView.getController(); 
     String coordinates[] = { 
      "1.352566007", "103.78921587" 
     }; 
     double lat = Double.parseDouble(coordinates[0]); 
     double lng = Double.parseDouble(coordinates[1]); 

     p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); 

     mc.animateTo(p); 
     mc.setZoom(17); 
     myMapView.invalidate(); 

    } 

    private final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      updateWithNewLocation(location); 
     } 

     public void onProviderDisabled(String provider) { 
      updateWithNewLocation(null); 
     } 

     public void onProviderEnabled(String provider) { 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 
    }; 

    /** Update the map with a new location */ 
    private void updateWithNewLocation(Location location) { 
     TextView myLocationText = (TextView) findViewById(R.id.myLocationText); 

     String latLongString; 

     if (location != null) { 
      // Update my location marker 
      positionOverlay.setLocation(location); 

      // Update the map location. 
      Double geoLat = location.getLatitude() * 1E6; 
      Double geoLng = location.getLongitude() * 1E6; 
      GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue()); 

      mapController.animateTo(point); 

      double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
      latLongString = "Lat:" + lat + "\nLong:" + lng; 

      Geocoder gc = new Geocoder(this, Locale.getDefault()); 

      try { 

       List<Address> addresses = gc.getFromLocation(lat, lng, 1); 
       StringBuilder sb = new StringBuilder(); 

       if (addresses.size() > 0) { 
        Address address = addresses.get(0); 

        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) 
         sb.append(address.getAddressLine(i)).append("\n"); 

        sb.append(address.getCountryName()); 
       } 
       addressString = sb.toString(); 
      } catch (IOException e) { 
      } 
     } else { 

      // Place the CellID here 
      latLongString = "No location found"; 

     } 
     // This commented out line will include latitute and longtitute 
     // myLocationText.setText("Your Phone is Currently at.. \n" + latLongString + "\n" + 
     // addressString); 

     myLocationText.setText("Your Phone is Currently at.. \n" + addressString); 
     setAddress(addressString); 

     ; 

    } 

    public void setAddress(String add) { 
     this.addressString = add; 
    } 

    public String getAddress() { 

     return addressString; 
    } 

    @Override 
    protected boolean isRouteDisplayed() { 
     return false; 
    } 
} 
+0

您是否收到任何錯誤?因爲你擁有的代碼是絕對正確的,所以我已經在我的應用程序中使用過,併爲我工作得很好。如果你有一些錯誤,請發佈錯誤日誌。 – Scorpion 2012-03-08 06:23:33

+0

Geocoder gc = new Geocoder(this,Locale.getDefault());而不是這個請試試這個。 Geocoder gc = new Geocoder(youractivityclassname.this.getApplicationContext(),Locale.getDefault()); – Scorpion 2012-03-08 06:25:56

回答

0

無論是地址傳遞給你的第二個ActivityIntent,或者如果你需要從你的第二個Activity做查詢,只需撥打Geocoder從那裏。

如果您想從第二個Activity實例化上述類(GetMapActivity)並調用getAddress方法,那麼這將不起作用。

0

下可能會奏效[代碼從的onCreate移動,把它放在一個方法]

public String getAddressString() { 
     if (addressString.equals("default") { 
      LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE); 
      Criteria crit = new Criteria(); 
      crit.setAccuracy(Criteria.ACCURACY_FINE); 
      String provider = lm.getBestProvider(crit, true); 
      updateWithNewLocation(lm.getLastKnownLocation(provider));    
     } 
     return addressString; 
    } 
10

我用下面的代碼在我的應用程序和它的工作對我來說絕對沒問題。嘗試這個。希望這會幫助你。

// 
    // Write the location name. 
    // 

    try { 

     Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault()); 
     List<Address> addresses = geo.getFromLocation(latitude, longitude, 1); 
     if (addresses.isEmpty()) { 
      yourtextfieldname.setText("Waiting for Location"); 
     } 
     else { 
      if (addresses.size() > 0) { 
       yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName()); 
       //Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 
    catch (Exception e) { 
     e.printStackTrace(); // getFromLocation() may sometimes fail 
    } 
+0

這會拋出「未找到Google Play服務資源,請檢查您的項目配置以確保資源已包含在內。」 – alicanbatur 2014-03-13 14:26:57

+0

它適合我! – Coeus 2015-11-20 20:37:01