Show Marker Of Current Position In Google Maps
I want to show the current position in google maps with a marker inside a Fragment class. The map is already shown, but I get a NullpointerException, when I initialize the MapFragm
Solution 1:
Your XML File
<FrameLayout
android:id="@+id/mapContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Java file code
FrameLayoutmapContainer= (FrameLayout) findViewById(R.id.mapContainer);
//show map of 40% of screenDisplayMetricsdm=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
LinearLayout.LayoutParamsparams=newLinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
params.height = (int) ((float) dm.heightPixels * (float) 0.5);
mapContainer.setLayoutParams(params);
FragmentManagerfm= getFragmentManager();
MapFragmentmapFragment= MapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapContainer, mapFragment).commit();
mapFragment.getMapAsync(newOnMapReadyCallback() {
@OverridepublicvoidonMapReady(GoogleMap googleMap) {
GoogleMapmMap= googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
addMarks(mMap);
Show marker on map
privatevoidaddMarks(GoogleMap googleMap) {
LatLngBounds.Builderbuilder=newLatLngBounds.Builder();
LatLnglatLng=newLatLng(lat1, long1);
builder.include(latLng);
MarkerOptionsmarkerOptions=newMarkerOptions();
markerOptions.position(latLng);
markerOptions.title(currentLocation);
googleMap.addMarker(markerOptions);
}
Solution 2:
Change this like below
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="400dp"class="com.google.android.gms.maps.MapFragment" />
to
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="400dp"class="com.google.android.gms.maps.SupportMapFragment" />
and
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
to
SupportMapFragment branchdetails_map =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
Post a Comment for "Show Marker Of Current Position In Google Maps"