有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java谷歌地图应用程序

我正在做一个项目,它将创建一个完整的谷歌地图示例

我试图编程一个imagebutton来跟踪和显示你自己的位置,但它似乎不起作用

MapsActivity。java

package com.example.ali.google安卓;

import 安卓.Manifest;
import 安卓.content.Context;
import 安卓.content.pm.PackageManager;
import 安卓.location.Criteria;
import 安卓.location.Location;
import 安卓.location.LocationManager;
import 安卓.support.v4.app.ActivityCompat;
import 安卓.support.v4.app.FragmentActivity;
import 安卓.os.Bundle;
import 安卓.support.v4.content.ContextCompat;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.view.View;
import 安卓.widget.ImageButton;
import 安卓.widget.Toast;

import com.google.安卓.gms.common.ConnectionResult;
import com.google.安卓.gms.common.GooglePlayServicesUtil;
import com.google.安卓.gms.common.api.GoogleApiClient;
import com.google.安卓.gms.location.LocationListener;
import com.google.安卓.gms.location.LocationRequest;
import com.google.安卓.gms.location.LocationServices;
import com.google.安卓.gms.maps.CameraUpdateFactory;
import com.google.安卓.gms.maps.GoogleMap;
import com.google.安卓.gms.maps.OnMapReadyCallback;
import com.google.安卓.gms.maps.SupportMapFragment;
import com.google.安卓.gms.maps.model.BitmapDescriptorFactory;
import com.google.安卓.gms.maps.model.CameraPosition;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.gms.maps.model.Marker;
import com.google.安卓.gms.maps.model.MarkerOptions;


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

    private static final int REQUEST_FINE_LOCATION = 0;

    private GoogleMap mMap;

    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;

    LatLng latLng;
    SupportMapFragment mFragment;


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

        loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_FINE_LOCATION);


        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        setContentView(R.layout.activity_maps);
//      setUpMapifNeeded();

        mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mMap = mFragment.getMap();

        mMap.setMyLocationEnabled(true);

        buildGoogleApiClient();

        mGoogleApiClient.connect();

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location myLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        Criteria criteria = new Criteria();

        String provider = locationManager.getBestProvider(criteria, true);

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }



        if ( myLocation != null) {

            double latitude = myLocation.getLatitude();
            double longitude = myLocation.getLongitude();


            LatLng latLng = new LatLng(latitude, longitude);


            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

            mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
            mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(" You are here!"));

        }



    }


    protected void onResume() {
        super.onResume();
        setUpMapifNeeded();
    }


    private void setUpMapifNeeded() {

        if (mMap == null) {

            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        }
        if (mMap != null) {
            setUpMap();
        }
    }


    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }


    public void TrackOwnLocation(View v) {

        mMap.setMyLocationEnabled(true);

        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        Criteria criteria = new Criteria();

        String provider = locationManager.getBestProvider(criteria, true);

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }

        Location mylocation = locationManager.getLastKnownLocation(provider);

        double latitude = mylocation.getLatitude();

        double longitude = mylocation.getLongitude();

        LatLng latLng = new LatLng(latitude, longitude);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(" You are here!"));

    }


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


    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();
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            //place marker at current position
            mMap.clear();
            latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            Marker m = mMap.addMarker(markerOptions);
        }

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000); //5 seconds
        mLocationRequest.setFastestInterval(3000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        //mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter

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


    }

    @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();
    }


    public void onLocationChanged(Location location) {

        //place marker at current position
        mMap.clear();
        latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        Marker m = mMap.addMarker(markerOptions);

        Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();

        //If you only need one location, unregister the listener
        //LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    }


    private void loadPermissions(String perm, int requestCode) {
        if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, perm)) {
                ActivityCompat.requestPermissions(this, new String[]{perm}, requestCode);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // granted
                } else {
                    // no granted
                }
                return;
            }

        }


    }

}

XML布局文件

<RelativeLayout
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:orientation="vertical"

    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓">



<fragment xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools="http://schemas.安卓.com/tools"
    xmlns:map="http://schemas.安卓.com/apk/res-auto" 安卓:layout_width="386dp"
    安卓:layout_height="380dp" 安卓:id="@+id/map" tools:context=".MapsActivity"
    安卓:name="com.google.安卓.gms.maps.SupportMapFragment" />

    <ImageButton
        安卓:layout_width="103dp"
        安卓:layout_height="103dp"
        安卓:id="@+id/DiaryEntry"
        安卓:adjustViewBounds="true"
        安卓:padding="20dp"
        安卓:scaleType="fitXY"

        安卓:layout_alignTop="@+id/trackownlocation"
        安卓:layout_alignParentEnd="true"
        安卓:layout_alignBottom="@+id/trackownlocation"
        安卓:src="@drawable/create_entry"
        安卓:background="@drawable/button_state"

        安卓:layout_alignParentStart="false" />

    <ImageButton
        安卓:onClick="TrackOwnLocation"
        安卓:layout_width="103dp"
        安卓:layout_height="103dp"
        安卓:id="@+id/trackownlocation"
        安卓:src="@drawable/own_location"
        安卓:adjustViewBounds="true"
        安卓:padding="20dp"
        安卓:scaleType="fitXY"
        安卓:layout_below="@+id/map"
        安卓:layout_alignParentStart="false"
        安卓:background="@drawable/button_state2"

        />

    <ImageButton
        安卓:layout_width="103dp"
        安卓:layout_height="103dp"
        安卓:id="@+id/help"
        安卓:adjustViewBounds="true"
        安卓:padding="20dp"
        安卓:scaleType="fitXY"

        安卓:src="@drawable/help"
        安卓:background="@drawable/button_state3"
        安卓:layout_alignTop="@+id/trackownlocation"
        安卓:layout_centerHorizontal="true"
        安卓:layout_marginTop="41dp" />



</RelativeLayout>

Android清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    package="com.example.ali.google安卓" >

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->


    <uses-sdk
        安卓:minSdkVersion="10"
        安卓:targetSdkVersion="22" />

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


    <permission
        安卓:name="com.example.ali.google安卓.permission.MAPS_RECEIVE"
        安卓:protectionLevel="signature" />

    <uses-permission 安卓:name="com.example.ali.google安卓.permission.MAPS_RECEIVE" />




    <uses-permission 安卓:name="安卓.permission.ACCESS_FINE_LOCATION" />



    <uses-permission 安卓:name="安卓.permission.INTERNET" />
    <uses-permission 安卓:name="安卓.permission.CAMERA" />
    <uses-permission 安卓:name="安卓.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission 安卓:name="安卓.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission 安卓:name="安卓.permission.ACCESS_NETWORK_STATE" />
    <uses-permission 安卓:name="安卓.permission.CHANGE_NETWORK_STATE" />
    <uses-permission 安卓:name="安卓.permission.ACCESS_WIFI_STATE" />
    <uses-permission 安卓:name="安卓.permission.CHANGE_WIFI_STATE" />
    <uses-permission 安卓:name="安卓.location.GPS_ENABLED_CHANGE" />
    <uses-permission 安卓:name="com.google.安卓.providers.gsf.permission.READ_GSERVICES" />



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

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            安卓:name="com.google.安卓.geo.API_KEY"
            安卓:value="@string/google_maps_key" />

        <activity
            安卓:name=".MapsActivity"
            安卓:label="@string/title_activity_maps" >
            <intent-filter>
                <action 安卓:name="安卓.intent.action.MAIN" />

                <category 安卓:name="安卓.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

共 (0) 个答案