如何在谷歌地图android上添加标记?

Posted

技术标签:

【中文标题】如何在谷歌地图android上添加标记?【英文标题】:How to add marker on google maps android? 【发布时间】:2017-12-25 17:42:04 【问题描述】:

我是 android 编程的初学者。我已经看过类似的问题和答案,但我仍然无法弄清楚为什么这不起作用。当我在模拟器上尝试这个并单击一个位置时,没有出现任何标记。这是我的代码:

编辑:当我现在点击以下代码时,我得到一个标记。当我第二次单击地图时,它只会给我一个运行时异常(NullPointer 异常):

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;
    

日志消息:

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)

【问题讨论】:

【参考方案1】:

在 Google 地图示例中查看此处 https://developers.google.com/maps/documentation/android-api/marker

如果你想在点击时添加标记,你也可以看这里: http://wptrafficanalyzer.in/blog/adding-marker-on-touched-location-of-google-maps-using-android-api-v2-with-supportmapfragment/

概念是像下面的代码那样做:

// Setting a click event handler for the map
    googleMap.setOnMapClickListener(new OnMapClickListener() 

        @Override
        public void onMapClick(LatLng latLng) 

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Setting the position for the marker
            markerOptions.position(latLng);

            // Setting the title for the marker.
            // This will be displayed on taping the marker
            markerOptions.title(latLng.latitude + " : " + latLng.longitude);

            // Clears the previously touched position
            googleMap.clear();

            // Animating to the touched position
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

            // Placing a marker on the touched position
            googleMap.addMarker(markerOptions);
        
    );

【讨论】:

现在可以使用了。我现在唯一的问题是,当添加一个标记时,下次我单击地图时应用程序会停止。 看来您的接收器泄漏了。查看崩溃日志中的这一行:JibeService has leaked IntentReceiver。尝试在服务的 onDestroy 中取消注册此接收器 (RcsReconfigurationSmsReceiver)。 这是迄今为止最方便的实现方式!谢谢@SagiMymon!【参考方案2】:
//Show Marker on a Location
googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE));

//Change Default Color of Marker

googleMap.addMarker(new MarkerOptions()
            .position(***LYN_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)));

【讨论】:

【参考方案3】:

获取用户当前位置的经纬度

        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);

【讨论】:

【参考方案4】:

以这种方式尝试。 传递您的纬度和经度值

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

// adding marker
googleMap.addMarker(marker);

【讨论】:

【参考方案5】:

MapsActivity 中的这段代码对我有用:

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


【讨论】:

以上是关于如何在谷歌地图android上添加标记?的主要内容,如果未能解决你的问题,请参考以下文章

按钮单击dialogFragment后如何在谷歌地图上添加标记?

单击标记时,新按钮会自动出现在谷歌地图(Android)上?如何删除?

用户如何在谷歌地图颤振上添加多个标记

如何在谷歌地图上添加多个标记

如何根据沿线的距离在谷歌地图折线上添加标记?

怎么在谷歌地图上做标记呀