web-dev-qa-db-fra.com

Comment ajouter un marqueur sur google maps android?

Je suis débutant en programmation Android. J'ai déjà examiné des questions et des réponses similaires, mais je ne comprends toujours pas pourquoi cela ne fonctionne pas. Lorsque j'essaie ceci sur l'émulateur et que je clique sur un emplacement, aucun marqueur n'apparaît. Ceci est mon code:

Edit: Je reçois un marqueur lorsque je clique maintenant avec le code suivant. Cela ne me donne une exception d'exécution (exception NullPointer) lorsque je clique sur la carte pour la deuxième fois:

    public class MapViewFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_map_view, container, false);
        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);
        mMapView.onResume();

        Context context = getActivity().getApplicationContext();

        final LocationsDB locationsDB = new LocationsDB(context);

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

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;
                googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                    public void onMapClick(LatLng point) {
                        // Drawing marker on the map
                        MarkerOptions markerOptions = new MarkerOptions();
                        markerOptions.position(point);
                        markerOptions.title(point.latitude + " : " + point.longitude);
                        googleMap.clear();
                        googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
                        googleMap.addMarker(markerOptions);
                        // Create location object
                        Location location = new Location(point.latitude, point.longitude);
                        // add location to SQLite database
                        locationsDB.insert(location);
                    }
                });
            }
        });
        return rootView;
    }
}

Journal des messages:

7-20 07:33:00.076 5359-5359/? W/RcsService: Java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.Android.rcs.service.service.a.a()' on a null object reference
                                                 at com.google.Android.rcs.service.e.b(SourceFile:43)
                                                 at com.google.Android.rcs.service.service.JibeService.onDestroy(SourceFile:162)
                                                 at Android.app.ActivityThread.handleStopService(ActivityThread.Java:3569)
                                                 at Android.app.ActivityThread.-wrap26(Unknown Source:0)
                                                 at Android.app.ActivityThread$H.handleMessage(ActivityThread.Java:1703)
                                                 at Android.os.Handler.dispatchMessage(Handler.Java:105)
                                                 at Android.os.Looper.loop(Looper.Java:164)
                                                 at Android.app.ActivityThread.main(ActivityThread.Java:6540)
                                                 at Java.lang.reflect.Method.invoke(Native Method)
                                                 at com.Android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.Java:240)
                                                 at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:767)


07-20 07:33:00.079 5359-5359/? E/ActivityThread: Service com.google.Android.rcs.service.service.JibeService has leaked IntentReceiver com.google.Android.rcs.service.provisioning.RcsReconfigurationSmsReceiver@741339 that was originally registered here. Are you missing a call to unregisterReceiver()?
                                                 Android.app.IntentReceiverLeaked: Service com.google.Android.rcs.service.service.JibeService has leaked IntentReceiver com.google.Android.rcs.service.provisioning.RcsReconfigurationSmsReceiver@741339 that was originally registered here. Are you missing a call to unregisterReceiver()?
                                                     at Android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.Java:1310)
                                                     at Android.app.LoadedApk.getReceiverDispatcher(LoadedApk.Java:1091)
                                                     at Android.app.ContextImpl.registerReceiverInternal(ContextImpl.Java:1397)
                                                     at Android.app.ContextImpl.registerReceiver(ContextImpl.Java:1370)
                                                     at Android.app.ContextImpl.registerReceiver(ContextImpl.Java:1358)
                                                     at Android.content.ContextWrapper.registerReceiver(ContextWrapper.Java:603)
                                                     at com.google.Android.rcs.service.provisioning.RcsSmsReceiver.a(SourceFile:12)
                                                     at com.google.Android.rcs.service.h.g(SourceFile:230)
                                                     at com.google.Android.rcs.service.h.<init>(SourceFile:212)
                                                     at com.google.Android.rcs.service.service.a.<init>(SourceFile:13)
                                                     at com.google.Android.rcs.service.e.a(SourceFile:32)
                                                     at com.google.Android.rcs.service.service.JibeService.d(SourceFile:145)
                                                     at com.google.Android.rcs.service.service.JibeService.onCreate(SourceFile:91)
                                                     at Android.app.ActivityThread.handleCreateService(ActivityThread.Java:3404)
                                                     at Android.app.ActivityThread.-wrap4(Unknown Source:0)
                                                     at Android.app.ActivityThread$H.handleMessage(ActivityThread.Java:1683)
                                                     at Android.os.Handler.dispatchMessage(Handler.Java:105)
                                                     at Android.os.Looper.loop(Looper.Java:164)
                                                     at Android.app.ActivityThread.main(ActivityThread.Java:6540)
                                                     at Java.lang.reflect.Method.invoke(Native Method)
                                                     at com.Android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.Java:240)
                                                     at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:767)
6
no-name

Obtenir la position actuelle de l'utilisateur latitude et longitude

        LatLng latLng = new LatLng(lat, lng);
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        mMap.clear();
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
        markerOptions.getPosition();
        mCurrLocationMarker = mMap.addMarker(markerOptions);
3
Manoj Vayu
//Show Marker on a Location
googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE));

//Change Default Color of Marker

googleMap.addMarker(new MarkerOptions()
            .position(BROOKLYN_BRIDGE)
            .title("First Pit Stop")
            .icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

//Replace Default Marker Icon with Custom Image

googleMap.addMarker(new MarkerOptions()
            .position(WALL_STREET)
            .title("Wrong Turn!")
            .icon(BitmapDescriptorFactory
            .fromResource(R.drawable.my_flag)));
1
Mukesh Kumar Swami

Ce code dans MapsActivity fonctionne pour moi:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {

private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;

public void centreMapOnLocation(Location location, String title){

    LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
    mMap.clear();
    mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

            Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            centreMapOnLocation(lastKnownLocation,"Your Location");
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}



@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    mMap.setOnMapLongClickListener(this);

    Intent intent = getIntent();
    if (intent.getIntExtra("Place Number",0) == 0 ){

        // Zoom into users location
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                centreMapOnLocation(location,"Your Location");
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                centreMapOnLocation(lastKnownLocation,"Your Location");
        } else {

            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }
    } else {

        Location placeLocation = new Location(LocationManager.GPS_PROVIDER);
        placeLocation.setLatitude(MainActivity.location.get(intent.getIntExtra("Place Number",0)).latitude);
        placeLocation.setLongitude(MainActivity.location.get(intent.getIntExtra("Place Number",0)).longitude);

        centreMapOnLocation(placeLocation,MainActivity.places.get(intent.getIntExtra("Place Number",0)));
    }


}


@Override
public void onMapLongClick(LatLng latLng) {
    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    String adress ="";
    try {
        List<Address> listaddress = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);

        if (listaddress != null && listaddress.size()>0){
            if (listaddress.get(0).getThoroughfare() != null){

                if (listaddress.get(0).getSubThoroughfare() != null){
                    adress += listaddress.get(0).getSubThoroughfare() + "";

                }
                adress += listaddress.get(0).getThoroughfare();
            }

        }

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

    mMap.addMarker(new MarkerOptions().position(latLng).title(adress));

    MainActivity.places.add(adress);
    MainActivity.location.add(latLng);
    MainActivity.arrayAdapter.notifyDataSetChanged();

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

}

}

0
Prateek Diwedi

essayez de cette façon . Passez vos valeurs de latitude et de longitude

// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");

// adding marker
googleMap.addMarker(marker);
0
Sunil P