2015-06-16 28 views
0

我已經做了一個應用程序,它使用GPS服務給你當前的經緯度。 現在我打算根據這個座標在MAP上顯示位置基於座標顯示在地圖上的位置android

我想創建2個活動。已經創建了第一個,我在TextView中顯示經度和緯度。在第二項活動中,我想要顯示哪個位置將顯示的地圖。從一個活動到另一個活動,我會在第一個活動中使用一個按鈕。

這裏是我的代碼(不是全部)

protected LocationManager locMan; 
protected LocationListener locLis; 
protected Context contex; 
TextView txtview; 
String lat,provider; 
protected String latitude,longtitude; 
protected boolean gps_enable,network_enable; 


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

    ActionBar bar = getActionBar(); 
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F44336"))); 

    txtview = (TextView)findViewById(R.id.locView); 

    locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 

} 

@Override 
public void onLocationChanged(Location loc){ 

    txtview = (TextView)findViewById(R.id.locView); 
    txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude()); 
} 

注: - 我是指javapapers網站,我目前的應用

問候

+0

的弟弟,他已經顯示在地圖並具有問題標記,但我的問題是差異。我有座標,我想根據座標顯示MAP的內容。 – user3384581

回答

0

創建地圖的活動,並通過束通過位置或將其保存在sharedpreference中

public class MapActivity extends ActionBarActivity{ 

private GoogleMap googleMap; 
FragmentManager fm; 
private Location mLocation; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    fm = getSupportFragmentManager(); 

    // get location from bundle or sharedprefs 
    // mLocation = ... 

    try { 
     if (googleMap == null) { 
      googleMap = ((SupportMapFragment) fm.findFragmentById(R.id.map)).getMap(); 
      googleMap.getUiSettings().setZoomGesturesEnabled(true); 
     } 
     googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    MarkerOptions TP = new MarkerOptions().title("title").position(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker)); 
    googleMap.addMarker(TP); 

}}  

此活動的xml佈局是

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<fragment 
    android:id="@+id/map" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"/> 

0

您需要使用MapViewMyLocationOverLay地圖,爲Android將會爲您處理顯示用戶的位置。

map=(MapView)findViewById(R.id.whatever_your_mapview_id_is); 
map.getOverlays().add(new MyLocationOverlay(this, map)); 

參見:display google maps using coordinates obtained using gps

+0

請注意,此代碼非常過時,使用Google Maps API v2,您只需調用'map.setMyLocationEnabled(true);' –

0

您可以使用LatLng對象,因爲它是parcelable通過位置地圖活動,見this answer

然後,您可以在MapsActivity中創建標記,並使用CameraPosition類將地圖視圖移動到指定位置。

首先,請確保您有當前位置雙重價值在您現有的活動:在您的onLocationChanged()回調

//instance variables: 
double lat; 
double lon; 

集經/緯度:

@Override 
public void onLocationChanged(Location loc){ 

    lat = loc.getLatitude(); //added 
    lon = loc.getLongitude(); //added 

    txtview = (TextView)findViewById(R.id.locView); 
    txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude()); 
} 

中創建一個按鈕,你的在現有活動中進行佈局,並在點擊監聽器中創建一個LatLng對象並將其以意圖發送給地圖活動:

Button b = (Button) findViewById(R.id.button); 
    b.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      LatLng fromPostion = new LatLng(lat, lon); 

      Bundle args = new Bundle(); 
      args.putParcelable("location", fromPostion); 

      Intent i = new Intent(this, MapsActivity.class); 
      i.putExtras(args); 
      startActivity(i); 
     } 
    }); 

然後,在你的地圖活動,你會從包獲得LatLng對象onCreate()

LatLng latlng; //Create as instance variable 

onCreate()

Bundle b = getIntent().getExtras(); 
    if (b != null){ 
     latlng = (LatLng) b.getParcelable("location"); 
    } 

然後,在該位置添加標記和設置相機位置和變焦:

private void setUpMap() { 

    mMap.getUiSettings().setMapToolbarEnabled(true); 
    mMap.getUiSettings().setZoomControlsEnabled(true); 
    mMap.setMyLocationEnabled(true); 


    MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location"); 

    // Changing marker icon 
    marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); 

    Marker m = mMap.addMarker(marker); 

    //move camera position and zoom to specified location 
    CameraPosition cameraPosition = new CameraPosition.Builder() 
      .target(latlng).zoom(8).build(); 

    mMap.animateCamera(CameraUpdateFactory 
      .newCameraPosition(cameraPosition)); 

} 

你的全地圖的活動可能是這個樣子:

public class MapsActivity extends ActionBarActivity implements 
     GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback { 

    private GoogleMap mMap; 
    LatLng latlng; 
    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 
    LocationManager manager; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_maps); 

     Bundle b = getIntent().getExtras(); 
     if (b != null){ 
      latlng = b.getParcelable("location"); 
     } 

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


     setUpMapIfNeeded(); 

     buildGoogleApiClient(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     setUpMapIfNeeded(); 


     if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
       !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ 
      AlertDialog.Builder builder = new AlertDialog.Builder(this) 
        .setTitle("Location is disabled") 
        .setMessage("Please enable your location") 
        .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100); 
         } 
        }); 

      AlertDialog dialog = builder.create(); 
      dialog.show(); 

     } else { 
      Log.v("Connection Status", String.valueOf(mGoogleApiClient.isConnected())); 
      mGoogleApiClient.connect(); 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == RESULT_OK && requestCode == 100) { 
      Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show(); 
      if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
        manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 

       Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show(); 
       //At least one provider enabled, connect GoogleApiClient 
       mGoogleApiClient.connect(); 

      } 
     } 
    } 

    @Override 
    protected void onPause(){ 
     super.onPause(); 
     if (mGoogleApiClient != null) { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 
    } 


    protected synchronized void buildGoogleApiClient() { 
     Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show(); 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show(); 

     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(10); 
     mLocationRequest.setFastestInterval(10); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
     mLocationRequest.setSmallestDisplacement(0.1F); 

     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 


    private void setUpMapIfNeeded() { 
     // Do a null check to confirm that we have not already instantiated the map. 
     if (mMap == null) { 
      // Try to obtain the map from the SupportMapFragment. 
      mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
        .getMap(); 

      // Check if we were successful in obtaining the map. 
      if (mMap != null) { 
       setUpMap(); 
      } 

     } 
    } 

    private void setUpMap() { 

     mMap.getUiSettings().setMapToolbarEnabled(true); 
     mMap.getUiSettings().setZoomControlsEnabled(true); 
     mMap.setMyLocationEnabled(true); 


     MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location"); 

     // Changing marker icon 
     marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); 

     Marker m = mMap.addMarker(marker); 

     //move camera position and zoom to specified location 
     CameraPosition cameraPosition = new CameraPosition.Builder() 
       .target(latlng).zoom(8).build(); 

     mMap.animateCamera(CameraUpdateFactory 
       .newCameraPosition(cameraPosition)); 


    } 


    @Override 
    public void onConnectionSuspended(int i) { 
     Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

     Log.d("locationtesting", "lat: " + location.getLatitude() + " lon: " + location.getLongitude()); 

    } 

} 

佈局XML爲MapsActivity:

<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" 
    android:name="com.google.android.gms.maps.SupportMapFragment" /> 

請注意,您還需要能夠在谷歌開發者控制檯谷歌地圖,以及包括谷歌播放在您的build.gradle文件(與您正在使用的版本更新版本)服務:

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:22.1.1' 
    compile 'com.google.android.gms:play-services:7.3.0' 
} 

的最後一件事是設置您的AndroidManifest.xml爲谷歌地圖API第2版:

權限:

<uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    <!-- 
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
     Google Maps Android API v2, but are recommended. 
    --> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

元數據標籤,確保他們的應用程序標籤中:

<meta-data 
     android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 
    <meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="Your-API-Key" /> 
+0

感謝兄弟。我將處理你的代碼。 – user3384581

+0

兄弟我已經顯示progressDialog微調,但我只想直到它提取的位置。如果找到座標,它應該停止顯示。 – user3384581

+0

@ user3384581只是關閉onLocationChanged()中的對話框。另外,如果您只需要一次位置更新,請務必在當時取消註冊回調。 –