2014-02-28 57 views
2

我想通過方法onTouchEvent()獲得緯度&經度。 但它沒有按照我的預期工作。 如何使用此方法獲取位置。使用onTouchEvent方法無法獲取經度和緯度

MapsActivity.java

public class MapsActivity<GeoPoint, OverlayItem> extends MapActivity implements 
     GooglePlayServicesClient.ConnectionCallbacks, 
     GooglePlayServicesClient.OnConnectionFailedListener, LocationListener { 

    private LocationManager manager; 

    private TextView tvAddress; 
    private Button btnSearch; 
    private EditText etSearch; 
    private LocationClient locationClient; 
    private GoogleMap googleMap; 
    private MapFragment mapFragment; 
    public Bundle mapOverlays; 
    MapView mapView; 
    GeoPoint p; 

    class MapOverlay extends com.google.android.maps.Overlay 
     { 
      @Override 
     public boolean onTouchEvent(MotionEvent e, 
       com.google.android.maps.MapView mapView) { 
      // TODO Auto-generated method stub 

       if(e.getAction()==1){ 
        com.google.android.maps.GeoPoint p = mapView.getProjection().fromPixels((int) e.getX(), (int) e.getY()); 
        Toast.makeText(getBaseContext(), 
          p.getLatitudeE6()/1E6 + "," + 
          p.getLongitudeE6() /1E6 , 
          Toast.LENGTH_SHORT).show(); 
       } 
      return false; 
     } 
     } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

     setContentView(R.layout.map); 

     manager = (LocationManager) getSystemService(LOCATION_SERVICE); 

     tvAddress = (TextView) findViewById(R.id.tvaddress); 
     btnSearch = (Button) findViewById(R.id.btnSearch); 
     etSearch = (EditText) findViewById(R.id.etSearch); 
     mapFragment = (MapFragment) getFragmentManager().findFragmentById(
       R.id.maps); 
     googleMap = mapFragment.getMap(); 
     locationClient = new LocationClient(this, this, this); 

    } 

    public void onSearch(View v) { 

     // Getting user input location 
     String location = etSearch.getText().toString(); 

     if (location != null && !location.equals("")) { 
      new GeocoderTask().execute(location); 
     } 
    } 

    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     locationClient.connect(); 
    } 

    @Override 
    protected void onPause() { 
     // TODO Auto-generated method stub 
     super.onPause(); 
     locationClient.disconnect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult result) { 

    } 

    @Override 
    public void onConnected(Bundle connectionHint) { 
     try { 

      Location currentLocation = locationClient.getLastLocation(); 
      double lat = currentLocation.getLatitude(); 
      double lng = currentLocation.getLongitude(); 
      // txtLocation.setText(lat + ", " + lng); 

      Geocoder geocoder = new Geocoder(this); 

      ArrayList<Address> address = (ArrayList<Address>) geocoder 
        .getFromLocation(currentLocation.getLatitude(), 
          currentLocation.getLongitude(), 5); 
      Address addr = address.get(0); 
      String currentAddress = (addr.getAddressLine(0) + "-" 
        + addr.getAdminArea() + "-" + addr.getLocality() + "-" 
        + addr.getPostalCode() + "-" + addr.getCountryCode()); 
      MarkerOptions options = new MarkerOptions(); 
      options.position(new LatLng(lat, lng)); 
      options.title(currentAddress); 
      options.snippet("Current location"); 
      options.icon(BitmapDescriptorFactory 
        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); 
      if (googleMap != null) { 
       googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
         new LatLng(lat, lng), 14.0f)); 
       googleMap.addMarker(options); 
      } else { 
       Toast.makeText(getApplicationContext(), "Map is null", 
         Toast.LENGTH_LONG).show(); 
      } 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

    @Override 
    public void onDisconnected() { 
     // TODO Auto-generated method stub 

    } 

    // An AsyncTask class for accessing the GeoCoding Web Service 
    private class GeocoderTask extends 
      AsyncTask<String, Void, ArrayList<Address>> { 

     @Override 
     protected ArrayList<Address> doInBackground(String... locationName) { 
      // Creating an instance of Geocoder class 
      Geocoder geocoder = new Geocoder(getBaseContext()); 
      ArrayList<Address> addresses = null; 

      try { 
       // Getting a maximum of 3 Address that matches the input text 
       addresses = (ArrayList<Address>) geocoder.getFromLocationName(
         locationName[0], 3); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return addresses; 
     } 

     @Override 
     protected void onPostExecute(ArrayList<Address> addresses) { 

      if (addresses == null || addresses.size() == 0) { 
       Toast.makeText(getBaseContext(), "No Location found", 
         Toast.LENGTH_SHORT).show(); 
       return; 
      } 

      // Clears all the existing markers on the map 
      googleMap.clear(); 

      // Adding Markers on Google Map for each matching address 
      for (int i = 0; i < addresses.size(); i++) { 

       Address address = (Address) addresses.get(i); 

       // Creating an instance of GeoPoint, to display in Google Map 
       LatLng latLng; 
       latLng = new LatLng(address.getLatitude(), 
         address.getLongitude()); 

       String addressText = String.format(
         "%s, %s", 
         address.getMaxAddressLineIndex() > 0 ? address 
           .getAddressLine(0) : "", address 
           .getCountryName()); 
       MarkerOptions markerOptions = new MarkerOptions(); 
       // markerOptions = new MarkerOptions(); 
       markerOptions.position(latLng); 
       markerOptions.title(addressText); 

       googleMap.addMarker(markerOptions); 

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

    @Override 
    protected boolean isRouteDisplayed() { 
     // TODO Auto-generated method stub 
     return false; 
    } 







} 

Mainfest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.mamun.tasktest" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="11" 
     android:targetSdkVersion="16" /> 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    <uses-permission android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 


    <permission 
     android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" > 
    </permission> 

    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <uses-library android:name="com.google.android.maps"/> 
     <activity 

      android:name="com.mamun.tasktest.MainActivity" 
      android:label="@string/app_name" 
      android:screenOrientation="portrait" > 
       <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 

     </activity> 

     <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="AIzaSyCgGng3iaqbTxJ3B_lYemZBEqXOonUtFEI" /> 
     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 
     <activity android:name=".MapsActivity" 
      android:screenOrientation="portrait" > 


     </activity> 


    </application> 

</manifest> 
+0

它不工作只爲觸摸事件或也爲click事件。 – Yugesh

+0

你是否嘗試過另一個活動生命時刻?我的意思是,'onCreate'例如 – MatheusJardimB

+0

不適用於任何事情@ Yugesh – user3076959

回答

0

使用此,它的作品對我來說

public class MainActivity extends FragmentActivity {  
     GoogleMap map; 
     ArrayList<LatLng> markerPoints; 

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



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

      // Getting Map for the SupportMapFragment 
      map = fm.getMap();  

      if(map!=null){ 

       // Enable MyLocation Button in the Map 
       map.setMyLocationEnabled(true);  

       // Setting onclick event listener for the map 
       map.setOnMapClickListener(new OnMapClickListener() { 

        @Override 
        public void onMapClick(LatLng point) { 
         point.latitude; 
        point.longitude; 
       }  
       }); 
      }  
     } 
} 

和清單文件

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="17" /> 

<uses-permission android:name="android.permission.INTERNET"/> 

<permission 
     android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 

<uses-permission android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.permission.MAPS_RECEIVE" /> 

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true"/> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="your api key" 

     /> 
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"></meta-data> 

</application> 

也作爲庫項目中添加谷歌播放服務庫您 project.some重要環節給出下面。

https://docs.google.com/document/pub?id=19nQzvKP-CVLd7_VrpwnHfl-AE9fjbJySowONZZtNHzw

How to add google-play-services.jar project dependency so my project will run and present map

http://developer.android.com/google/play-services/setup.html#Install

+0

在point.latitude之間以分號顯示錯誤;(here)point.longitude; – user3076959

+0

@ user3076959您可以很容易地將緯度作爲double latitute = point.latitude;和經度爲雙經度= point.longitude;只需替換兩條線或將值初始化爲變量即可。 –