我的位置butoon和我当前的位置没有出现

时间:2016-11-07 06:27:12

标签: android google-maps

我有下面的代码用于显示包含当前位置和我的位置按钮的地图,但

我的位置按钮没有出现,我的位置没有出现!! 我认为代码安排有一些问题。 但我没有找到原因。

import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
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.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wneet.white.ModelsClientInfo.Address;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import cn.pedant.SweetAlert.SweetAlertDialog;


public class select_position extends RunTimePermisions implements   GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    GoogleMap.OnInfoWindowClickListener,
    GoogleMap.OnMapClickListener,
    GoogleMap.OnMarkerClickListener {

    private static final int REQUEST_PERMISSIONS = 20;

    Double USER_LATITUDE;
    Double USER_LONGITUDE;
    protected Context context;
    private GoogleMap googleMap;
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;

    Marker marker, markerStartpoint, markerEndpoint;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    Spinner chooseAddresses;
    Button select_position;
    Address currentAddress;
    Geocoder geocoder;
    TextView startPoint, endPoint;
    int service_type;
    RelativeLayout StartPointLayout, EndPointLayout;
    boolean isStartPointClicked ;
    LatLng StartValue,EndValue;

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

        select_position.super.requestAppPermissions(new
                        String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CONTROL_LOCATION_UPDATES}, R.string
                        .runtime_permissions_txt
                , REQUEST_PERMISSIONS);

        Button back_btn = (Button) findViewById(R.id.back);

        back_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                finish();

            }
        });

        //get info from preveous activity
        final Intent service_intent = getIntent();

        // WhiteModel x = (WhiteModel) addresses_intent.getSerializableExtra("Service_Type");
        WhiteModel model = (WhiteModel) service_intent.getSerializableExtra("service_Model");


        final String service_id = model.getService_id();
        Log.e("serviceId  position", service_id + "");
        final Double cost = model.getCost();
        Log.e("cost position", cost + "");
        final String user_id = getIntent().getStringExtra("user_id");
        Log.e("user id position", user_id + "");
        final String token = getIntent().getStringExtra("token");
        final String title = model.getTitle();
        Log.e("title  position", title + "");

        final String details = model.getDetails();
        Log.e("details position", details + "");

        service_type = model.getService_type();
        Log.e("serviceType select pos.", service_type + "");

        select_position = (Button) findViewById(R.id.select_position);

        select_position.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent_data = new Intent(select_position.this, order_Summary.class);
                intent_data.putExtra("user_latitude", USER_LATITUDE);
                Log.e(" user_latitude", USER_LATITUDE + "");
                intent_data.putExtra("user_longitude", USER_LONGITUDE);
                Log.e(" user_longitude", USER_LONGITUDE + "");

                intent_data.putExtra("token", token);
                Log.e("token position ", token + "");

                intent_data.putExtra("user_id", user_id);
                intent_data.putExtra("service_id", service_id);
                Log.e("serviceId po ", service_id + "");
                intent_data.putExtra("title", title);
                intent_data.putExtra("cost", cost);
                intent_data.putExtra("details", details);               

                }
                if((StartValue!=null) && (EndValue !=null)) {

                    intent_data.putExtra("StartValue lat", StartValue.latitude);
                    intent_data.putExtra("StartValue lng", StartValue.longitude);
                    intent_data.putExtra("EndValue lat", EndValue.latitude);
                    intent_data.putExtra("EndValue lng", EndValue.longitude);
                    startActivity(intent_data);

                }

                else
                startActivity(intent_data);
            }
        });

        try {
            initilizeMap();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MapsInitializer.initialize(getApplicationContext());
    }

    @Override
    public void onPermissionsGranted(int requestCode) {
        Toast.makeText(this, "Permissions Received.", Toast.LENGTH_LONG).show();
    }

    private void initilizeMap() {

        try {
            if (googleMap == null) {
                MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
                mapFragment.getMapAsync(new OnMapReadyCallback() {
                    public GoogleMap googleMap;

                    @Override
                    public void onMapReady(GoogleMap gMap) {
                        this.googleMap = gMap;

                        mGoogleApiClient.connect();
                    }
                });
           //continue
                MapsInitializer.initialize(getApplicationContext());
                mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
                initListeners();

                // Get the button view
                View locationButton = ((View) findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));

                // and next place it, for exemple, on bottom right (as Google Maps app)
                RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
                rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
                rlp.setMargins(0, 0, 400, 400);
            }

        } catch (Exception e) {
            Log.e("map intialize ", e.toString());
        }
    }

    private void initListeners() {
        googleMap.setOnMarkerClickListener(this);
        googleMap.setOnInfoWindowClickListener(this);
        googleMap.setOnMapClickListener(this);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

    @Override
    public void onConnected(Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // 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 ActivityCompat#requestPermissions for more details.
            return;
        }
        googleMap.setMyLocationEnabled(true);

        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("يرجى تفعيل خاصية تحديد الموقع");
            dialog.setPositiveButton("افتح الإعدادات", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    paramDialogInterface.dismiss();
                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                }
            });
            dialog.setNegativeButton("الغاء", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    paramDialogInterface.dismiss();
                }
            });
            dialog.show();
            mCurrentLocation = new Location("");
            mCurrentLocation.setLatitude(15.0000);
            mCurrentLocation.setLongitude(48.0000);
            initCamera(mCurrentLocation, false);
        } else {

            if (mCurrentLocation == null) {
                mCurrentLocation = new Location("");
                mCurrentLocation.setLatitude(15.0000);
                mCurrentLocation.setLongitude(48.0000);
                initCamera(mCurrentLocation, false);
            } else {
                initCamera(mCurrentLocation, true);
            }
        }
    }

    private void initCamera(Location location, Boolean conn) {
        CameraPosition position;
        if (conn) {
            position = CameraPosition.builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(15f).bearing(0.0f).tilt(0.0f).build();
        } else {
            position = CameraPosition.builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(5f).bearing(0.0f).tilt(0.0f).build();
        }
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));

        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setTrafficEnabled(false);

        String LATITUDE = (location.getLatitude() + " ");
        String LONGITUDE = (location.getLongitude() + " ");

        String DEV_LATITUDE = (location.getLatitude() + " ");
        String DEV_LONGITUDE = (location.getLongitude() + " ");
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        mCurrentLocation = new Location("");
        mCurrentLocation.setLatitude(15.0000);
        mCurrentLocation.setLongitude(48.0000);
        initCamera(mCurrentLocation, false);
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (currentAddress != null) {
            //make it null to remove the first one

            currentAddress = null;
        }
        Log.e("condition ", String.valueOf(service_type ==1));
        boolean condition = service_type == 1;
        Log.e("condition", condition + "");

        if (service_type ==1) {
            Log.e("service type mapclick", service_type + "");

            if (isStartPointClicked) {
                getStartAddress(latLng);

            } else {

                getEndAddress(latLng);
            }

        } else {
            selectPoint(latLng);
            Log.e("service type mapclick2", service_type + "");
        }
    }

    void selectPoint(LatLng latLng) {
        if (marker != null) {
            marker.remove();
        }

        MarkerOptions options = new MarkerOptions().position(latLng);
        options.icon(BitmapDescriptorFactory.defaultMarker());
        marker = googleMap.addMarker(options);

        USER_LATITUDE = Double.valueOf(latLng.latitude + " ");
        Toast.makeText(select_position.this, "latitude " + USER_LATITUDE, Toast.LENGTH_LONG);
        Log.e("my latitude", USER_LATITUDE + "");
        USER_LONGITUDE = Double.valueOf(latLng.longitude + " ");
        Toast.makeText(select_position.this, "longitude " + USER_LONGITUDE, Toast.LENGTH_LONG);
        Log.e("Longitude", USER_LONGITUDE + "");

        //update map location

        CameraPosition position = CameraPosition.builder().target(latLng).zoom(15f).bearing(0.0f).tilt(0.0f).build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
    }

    void getStartAddress(final LatLng Startpoint) {
        startPoint = (TextView) findViewById(R.id.startPointTV);

        List<android.location.Address> addresses = new ArrayList<>();
        try {
            Log.e("point latlng", Startpoint + "");
            geocoder = new Geocoder(this, Locale.ENGLISH);
            addresses = geocoder.getFromLocation(Startpoint.latitude, Startpoint.longitude, 1);
        } catch (IOException e) {
            e.toString();
            Log.e("error getAddress", e.toString());
        }

        final android.location.Address address = addresses.get(0);

        if (address != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                sb.append(address.getAddressLine(i) + "\n");
                Log.e("address from geo", sb + "");
                startPoint.setText(sb);
                // Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
            }

            //remove previously placed Marker
            if (markerStartpoint != null) {
                markerEndpoint.remove();
            }

                //place marker where user just clicked
                markerStartpoint = googleMap.addMarker(new MarkerOptions().position(Startpoint).title("Marker")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
            StartValue=Startpoint;

            }
        }

    void getEndAddress(LatLng Endpoint) {

        endPoint = (TextView) findViewById(R.id.endPointTV);

        List<android.location.Address> addresses = new ArrayList<>();
        try {
            Log.e("point latlng", Endpoint + "");
            geocoder = new Geocoder(this, Locale.ENGLISH);
            addresses = geocoder.getFromLocation(Endpoint.latitude, Endpoint.longitude, 1);
        } catch (IOException e) {
            e.toString();
            Log.e("error getAddress", e.toString());
        }

        final android.location.Address address = addresses.get(0);

        if (address != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                sb.append(address.getAddressLine(i) + "\n");
                Log.e("address from geo", sb + "");
                endPoint.setText(sb);
                // Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
            }

            //remove previously placed Marker
            if (markerEndpoint != null) {
                markerEndpoint.remove();
            }

            //place marker where user just clicked
            markerEndpoint = googleMap.addMarker(new MarkerOptions().position(Endpoint).title("Marker")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

            EndValue=Endpoint;
        }


        StartPointLayout = (RelativeLayout) findViewById(R.id.StartPointLayout);
        EndPointLayout = (RelativeLayout) findViewById(R.id.EndPointLayout);

        StartPointLayout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                isStartPointClicked = true;
                Log.e("is start point",isStartPointClicked+"");
            }
        });

        EndPointLayout.setOnClickListener(new View.OnClickListener()

                                          {

                                              @Override
                                              public void onClick(View v) {


                                                  isStartPointClicked = false;

                                                  Log.e("is end point",isStartPointClicked+"");

                                              }
                                          }

        );
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap=googleMap;
    }
}

提前预订..

2 个答案:

答案 0 :(得分:0)

你使用过棉花糖权限吗?

@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == MY_LOCATION_REQUEST_CODE) { if (permissions.length == 1 && permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } else { // Permission was denied. Display an error message. } }

答案 1 :(得分:0)

多数民众赞成我怎么做,可能会对你有用。 在转到您要使用我的位置图标的活动之前获取位置权限,并使用this.googleMap.setMyLocationEnabled(true);在onMapReady()函数中。