2016-02-03 2 views
0

У меня есть активность под названием LocationTest и в моем приложении, которые получают широту и долготу, и она работает правильно. Это действие включает в себя кнопку, которая приведет нас к другому действию, которое называется MapLocation, которое графически отображает расположение на map.But, когда я нажимаю на приложении перестанет working.I разместит код 2 деятельности, если кто-то может помочь plz.I думает, что ошибка во второй активностиПолучить графическую карту в Android Studio

LocationTest активности

public class LocationTest extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener { 


private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi; 
private GoogleApiClient googleApiClient; 
private LocationRequest locationRequest; 
public final static int MILLISECONDS_PER_SECOND=1000; 
public final static int MINUTE = 60*MILLISECONDS_PER_SECOND; 
private double longitude=0; 
private double latitude=0; 
private TextView lblLong; 
private TextView lblLat; 

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

    //this here is for the map 
    Button mapBtn =(Button)findViewById(R.id.mapBtn); 
    googleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 

    mapBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent=new Intent(LocationTest.this,MapLocation.class); 
      startActivity(intent); 
     } 
    }); 
    locationRequest= new LocationRequest(); 
    /*locationRequest.setInterval(MINUTE);*/ 
    locationRequest.setInterval((MINUTE)); 
    locationRequest.setFastestInterval(15 * MILLISECONDS_PER_SECOND); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    lblLong = (TextView)findViewById(R.id.lblLong); 
    lblLat = (TextView)findViewById(R.id.lblLat); 



} 

@Override 
protected void onStart() { 
    super.onStart(); 
    googleApiClient.connect(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    googleApiClient.disconnect(); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    if(googleApiClient.isConnected()){ 
     requestLocationUpdates(); 
    } 
} 

@Override 
public void onConnected(Bundle bundle) { 
    requestLocationUpdates(); 
} 

    private void requestLocationUpdates() { 
     LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); 

    } 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onLocationChanged(Location location) { 

    Toast.makeText(this, "Your Location Has Been Set: " + location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_LONG).show(); 
    longitude = location.getLongitude(); 
    latitude = location.getLatitude(); 
    lblLong.setText(Double.toString(longitude)); 
    lblLat.setText(Double.toString(latitude)); 


} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 

} 
} 

КартаЗакрыть Деятельность

public class MapLocation extends AppCompatActivity implements LocationListener{ 


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

    if (!isGooglePlayServicesAvailable()) { 
     finish(); 
    } 
    setContentView(R.layout.activity_map_location); 
    SupportMapFragment supportMapFragment = 
      (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap); 
    googleMap = supportMapFragment.getMap(); 
    googleMap.setMyLocationEnabled(true); 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    String bestProvider = locationManager.getBestProvider(criteria, true); 
    Location location = locationManager.getLastKnownLocation(bestProvider); 

    if (location != null) { 
     onLocationChanged(location); 
    } 
    locationManager.requestLocationUpdates(bestProvider, 20000, 0, this); 
} 
@Override 
public void onLocationChanged(Location location) { 
    TextView locationTv = (TextView) findViewById(R.id.latlongLocation); 
    double latitude = location.getLatitude(); 
    double longitude = location.getLongitude(); 
    LatLng latLng = new LatLng(latitude, longitude); 
    googleMap.addMarker(new MarkerOptions().position(latLng)); 
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 
    locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude); 
} 

@Override 
public void onProviderDisabled(String provider) { 
    // TODO Auto-generated method stub 
} 

@Override 
public void onProviderEnabled(String provider) { 
    // TODO Auto-generated method stub 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 
} 

private boolean isGooglePlayServicesAvailable() { 
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
    if (ConnectionResult.SUCCESS == status) { 
     return true; 
    } else { 
     GooglePlayServicesUtil.getErrorDialog(status, this, 0).show(); 
     return false; 
    } 
} 


} 
+0

Добавить журнал аварийного – Natan

+0

Я новичок в разработке мобильных приложений, я не знаю, что это аварийный журнал. Можете ли вы мне помочь с кодом, пожалуйста. – Deve

ответ

0

Для того, чтобы показать карту в вашем приложении, вам потребуется выполнить следующие действия:

1) Получите вы ключ API от https://developers.google.com/maps/documentation/android-api/ и установить права доступа, как это в вашем файле манифеста:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="Your package name" > 
    ... 
    <!-- Creating Permission to receive Google Maps --> 
    <permission 
     android:name="com.arshad.map.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 

    <!-- Permission to receive Google Maps --> 
    <uses-permission android:name="com.arshad.map.permission.MAPS_RECEIVE" /> 

    <!-- Maps API needs OpenGL ES 2.0. --> 
    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 

     ... 

     <!-- Maps API --> 
     <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="Replace with your API key" /> 

     ... 
    </application> 
</manifest> 

2) Ниже приведен пример с использованием фрагментов:

import android.Manifest; 
import android.app.Fragment; 
import android.app.FragmentTransaction; 
import android.content.pm.PackageManager; 
import android.os.Bundle; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.app.FragmentActivity; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

import R; 

public class MapFragment extends Fragment implements OnMapReadyCallback { 

    private static final String ARG_LONGITUDE = "longitude"; 
    private static final String ARG_LATITUDE = "latitude"; 
    private static final String LOG_TAG = MapFragment.class.getSimpleName(); 

    private String mLongitude; 
    private String mLatitude; 

    //Google maps parameters initialization 
    static LatLng location = new LatLng(21, 57); 

    public static MapFragment newInstance(String longitude, String latitude) { 
     MapFragment fragment = new MapFragment(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_LONGITUDE, longitude); 
     args.putString(ARG_LATITUDE, latitude); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (getArguments() != null) { 
      //Get lattitude and longitude 
      mLongitude = getArguments().getString(ARG_LONGITUDE); 
      mLatitude = getArguments().getString(ARG_LATITUDE); 
      Log.d(LOG_TAG, "Long = " + mLongitude + " lat = " + mLatitude); 
     } 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view = inflater.inflate(R.layout.fragment_map, container, false); 

     MapFragment mapFragment = new MapFragment(); 
     FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); 
     transaction.add(R.id.rl_map_container, mapFragment).commit(); 

     mapFragment.getMapAsync(this); 

     return view; 
    } 

    @Override 
    public void onMapReady(GoogleMap map) { 

     //Setting the position of camera in the important location 
     map.moveCamera(CameraUpdateFactory.newLatLngZoom(
       new LatLng(Double.valueOf(mLatitude), Double.valueOf(mLongitude)), 17)); 
     //Adding a marker with customized icon 
     map.addMarker(new MarkerOptions() 
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_<Your icon name>)) 
       .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left 
       .position(new LatLng(Double.valueOf(mLatitude), Double.valueOf(mLongitude)))); 

     // MAP_TYPE_TERRAIN, MAP_TYPE_HYBRID and MAP_TYPE_NONE 
     map.setMapType(GoogleMap.MAP_TYPE_NORMAL); 


    } 
} 

3) Сделайте ваш макет так:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    tools:context=".fragments.MapFragment" 
    > 

    <FrameLayout 
     android:id="@+id/rl_map_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</RelativeLayout> 

Кроме того, вы можете получить более подробную информацию в https://developers.google.com/maps/documentation/android-api/

Смежные вопросы