Create a Marker at the current Maps position with Fragment

Asked

Viewed 286 times

0

Hello, I need to put a Marketer in my current position and show on Google Maps, but as I am using Fragment the setMyLocationEnabled method does not work, I have already gone after the internet on several websites and did not find the solution, so I decided to ask here, here is my code

package com.outlier.br.sos_carro.activity.OficinaActivity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
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.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.outlier.br.sos_carro.R;
import com.outlier.br.sos_carro.model.Oficina;

/**
 * Created by daniel on 9/18/16.
 */
public class TabLocalizacaoFragments extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;
    Oficina oficina;



    public void setOficina(Oficina oficina) {
        this.oficina = oficina;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.tab_oficina_localizacao, container, false);

        mMapView = (MapView) rootView.findViewById(R.id.mapview);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }


        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {

                googleMap = mMap;
                // For dropping a marker at a point on the Map
                LatLng latLng = new LatLng(oficina.getLatitude(), oficina.getLongitude());
                MarkerOptions options = new MarkerOptions()
                        .position(latLng)
                        .title(oficina.getNome())
                        .snippet(oficina.getDescricao());
                /*
                carro = new MarkerOptions()
                        .position(latLng)
                        .title("Minha posiçao");*/
                googleMap.addMarker(options);

                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(15).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            }
        });

        return rootView;
    }


}

Thanks for your help

1 answer

2

You can use the setMyLocationEnabled() in the method onMapReady() There’s a reference to the map.

Do so:

mMapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap mMap) {

        mMap.setMyLocationEnabled(true);

        //Apenas para fazer zoom - ver nota
        double lat;
        double long;
        Location location = mMap.getMyLocation();

        if (location != null) {
            lat = location.getLatitude();
            long = location.getLongitude();
        } 
        LatLng minhaLocalizacao = new LatLng(lat, long);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(minhaLocalizacao, 3));
    }
});

Note:

  • You will have to deal with runtime permissions if the targetApi is 23 or more.

  • The method getMyLocation() is considered obsolete, it is used here because it is intended that the camera zoom at those coordinates. A documentation suggests that the zoom must be done by the user using the button at the top corner of the map.

  • Mas, para lidar com as permissões, tenho que pôr esta linha if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != Packagemanager.PERMISSION_GRANTED) { But, this gives error, for being working with Fragment, not with Activity

  • Instead of this use getActivity(): ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)

  • On the other hand you can check the permission in Activity, before creating Fragment.

  • Why are you creating a map Fragment? Why not use the class Supportmapfragment?

  • Hello friend, this is a teamwork, for a college discipline and we do not have much experience with Android, this code above, shows the location of a workshop on the map and at the end we want to show a route between the current point and this workshop. Therefore, I am adapting the code for this purpose, but I found this series of problems... The getMyLocation method definitely did not work, not showing the location on the map.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.