Marker not moving on Google MapView - android

I implement google map view inside fragment, everything is working but Marker is not moving into new location its fixed. I tried long press,listeners,tapping on other part of map, Nothing works.
MapView Fragment
public class MapLocation_Fragment extends Fragment implements GoogleMap.OnMarkerDragListener,GoogleMap.OnMarkerClickListener,OnMapReadyCallback {
MapView mapView;
GoogleMap google_Map;
Marker Map_marker;
LatLng locclPosition;
double lati,longi;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.maplocation_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.send_Location_MapView);
mapView.onCreate(savedInstanceState);
mapView.onResume();// Needed tog et the map to display immediately
lati=getArguments().getDouble("lat");
longi=getArguments().getDouble("longi");
locclPosition=new LatLng(lati,longi);
MapsInitializer.initialize(getActivity());
mapView.getMapAsync(this);
return view;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMarkerDragStart(Marker marker) {
Map_marker=marker;
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
google_Map = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
google_Map.setOnMarkerClickListener(MapLocation_Fragment.this);
google_Map.setOnMarkerDragListener(MapLocation_Fragment.this);
google_Map.setTrafficEnabled(true);
google_Map.setBuildingsEnabled(true);
google_Map.setMapType(googleMap.MAP_TYPE_NORMAL); //THIS OPTION WILL SHOW MAP IN SATELLITE FORM
google_Map.addMarker(new MarkerOptions()
.position(locclPosition)
.title("Current Location")
.draggable(true));
CameraPosition cameraPosition=new CameraPosition.Builder().target(locclPosition).zoom(19).build();
google_Map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
I need to marker to move where ever user tap on map but after lot of effort its still not moving at all. Please help guys.

To make your marker move when dragging it you need to write some code in your onMarkerDragEnd method, basically to update the position of your marker (locclPosition) to where the dragging ends (new coordinates)
#Override
public void onMarkerDragEnd(Marker marker) {
locclPosition = marker.getPosition();
}

Related

How to give the GoogleMap API inside a fragment a specific map seach

So, I basically put a GoogleMaps API inside a fragment in my app, and I want to give it a specific default search like we do with Intent, but in this case im using fragment instead of an intent.`public class LocalGymsFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_local_gyms, 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 sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}`
I suggest that you try implementing the GoogleMaps API on a constraint layout or new GoogleMaps Activity. This is because Fragments aren't just a cup of tea. It is tough implementing this on fragments.

NavigationDrawer + Google maps event

I have a problem with pressing an option in my navigationView (R.id.create_marker) I want to create a marker in my MapFragment, but I can not do it, any suggestions?
Code of MainActivity.java where I press the menu option:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.create_marker:
Toast.makeText(MainActivity.this, "Crear Marker", Toast.LENGTH_SHORT).show();
// Create marker and display it on the map
break;
}
return false;
}
});
Code of MapFragment.java:
public class MapFragment extends Fragment
implements OnMapReadyCallback {
private View rootView;
private GoogleMap gMap;
private MapView mapView;
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_map, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) rootView.findViewById(R.id.map);
if (mapView != null) {
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
This is the structure of my project:
To create a marker, you need to call addMarker method on your Map, once it's ready to be used.
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
If you want your Map to open a marker for a fixed Lat-Lng, pass in the coordinates as shown in the code above, otherwise request location via Google Location Api and pass the obtained Lat-Lng values to the addMarker() method.

Google maps loading slow inside fragment

I have main activity with fragments and one of the fragments is Map Fragment. Now, when i tap there, every time it opens slow. I am using singleton instance of fragment, but it still doesnt work as expected. Here is a good of that class:
public MapsFragment() {
gson = new Gson();
}
public static MapsFragment getInstance() {
if (mInstance == null)
mInstance = new MapsFragment();
return mInstance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_maps, container, false);
mOnSavedinstance = savedInstanceState;
mMapView = (MapView) v.findViewById(R.id.map);
mMapWrapperLayout = (MapWrapperLayout) v.findViewById(R.id.map_relative_layout);
mMapView.getMapAsync(MapsFragment.this);
mMapView.onCreate(savedInstanceState);
mMapView.requestFocus();
MapsInitializer.initialize(getActivity());
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mMapWrapperLayout.init(mGoogleMap, Constants.MARKER_HEIGHT);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(false);
}
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
setUpMap();
}
private void setUpMap() {
new Thread(new Runnable() {
#Override
public void run() {
final ArrayList<MarkerOptions> markerOptionses = new ArrayList<MarkerOptions>();
int counter = 0;
for (final Places places : Model.getInstance().getPlaces()) {
LatLng location = new LatLng(Double.parseDouble(places.getLat()), Double.parseDouble(places.getLon()));
final MarkerOptions options = new MarkerOptions();
options.snippet(gson.toJson(places));
options.position(location);
options.title(String.valueOf(counter));
markerOptionses.add(options);
counter++;
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (MarkerOptions markerOptionse : markerOptionses) {
mGoogleMap.addMarker(markerOptionse).setIcon(BitmapDescriptorFactory.fromResource(Model.getInstance().getPlaces()
.get(Integer.parseInt(markerOptionse.getTitle())).getMapsRes(getActivity())));
}
}
});
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(45.4654, 9.1859)) // Sets the center of the map to location user
.zoom(Constants.CAMERA_ZOOM_LOCATION) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnMapClickListener(MapsFragment.this);
// mGoogleMap.setOnInfoWindowClickListener(mInfoListener);
}
});
}
}).start();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleMap.clear();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
You can try to add markers only if it would be visible? I mean: first move camera to start position and set zoomLevel and just after that add Markers but only if it's in visible sector. And update markers on camera move.

How to change map view on fragment?

I'm developing an app by using mapbox api. At the map when the user clicks map item on menu a fragment is opening.Later user may want to change mapview style such as satellite,dark,emerald or just a street view. User is able to choose map style on action bar. I implemented my action bar on main activity. When the user on map fragment choose map style and a variable comes to fragment which handled in main activity. This variable is the string of map style. Now I want to change map view style without recreating map fragment. What can you advise about this problem ?
public class GeoMapFragment extends Fragment implements OnMapReadyCallback {
public MapView mapView = null;
private MapboxMap mapboxMap;
public String mapViewSelectedItem ;
private static final int PERMISSIONS_LOCATION = 0;
public GeoMapFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_geomap, container, false);
mapView = (MapView)view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// Inflate the layout for this fragment
return view;
}
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
/**
* Dispatch onPause() to fragments.
*/
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.setStyle(Style.DARK);
mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(0, 0)));
// Show user location (purposely not in follow mode)
if ((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
mapboxMap.setMyLocationEnabled(true);
}
// TODO - mv.loadFromGeoJSONURL("https://gist.githubusercontent.com/tmcw/10307131/raw/21c0a20312a2833afeee3b46028c3ed0e9756d4c/map.geojson");
mapboxMap.addMarker(new MarkerOptions().title("Edinburgh").snippet("Scotland").position(new LatLng(55.94629, -3.20777)));
mapboxMap.addMarker(new MarkerOptions().title("Stockholm").snippet("Sweden").position(new LatLng(59.32995, 18.06461)));
mapboxMap.addMarker(new MarkerOptions().title("Prague").snippet("Czech Republic").position(new LatLng(50.08734, 14.42112)));
mapboxMap.addMarker(new MarkerOptions().title("Athens").snippet("Greece").position(new LatLng(37.97885, 23.71399)));
mapboxMap.addMarker(new MarkerOptions().title("Tokyo").snippet("Japan").position(new LatLng(35.70247, 139.71588)));
mapboxMap.addMarker(new MarkerOptions().title("Ayacucho").snippet("Peru").position(new LatLng(-13.16658, -74.21608)));
mapboxMap.addMarker(new MarkerOptions().title("Nairobi").snippet("Kenya").position(new LatLng(-1.26676, 36.83372)));
mapboxMap.addMarker(new MarkerOptions().title("Canberra").snippet("Australia").position(new LatLng(-35.30952, 149.12430)));
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapboxMap.setMyLocationEnabled(true);
}
}
}
}
Your map fragment should have a getMapAsync() call which you can change the style of. Heres a rough example of how you can accomplish this:
private MapboxMap map;
...
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
}
});
...
// Wherever you implemented receiving the style string from MainActivity you can include this:
map.setStyleUrl(<style url>);
If this doesn't work for you, please let me know how exactly you are creating the map fragment. Currently the SDK includes a fragment already which you can setup like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment;
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
LatLng patagonia = new LatLng(-52.6885, -70.1395);
MapboxMapOptions options = new MapboxMapOptions();
options.accessToken("<your access token here>");
options.styleUrl(Style.SATELLITE);
options.camera(new CameraPosition.Builder()
.target(patagonia)
.zoom(9)
.build());
mapFragment = SupportMapFragment.newInstance(options);
transaction.add(R.id.container, mapFragment, "mapFragment");
transaction.commit();
} else {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("mapFragment");
}
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
}
});
}
If you did it this way you can easily change the style of the map like I said above.
Hope this helps out!

Android: MapView not responding after Resume

I have a strange problem with a com.google.android.gms.maps.MapView.
To check if my App crashes after the garbage collector is doing his job i force my HTC One (4.2.2) to allow only 1 running app in background. If I leave my app(home button) while showing a MapView, start any other app and resume to my app, my MapView is still showing up...but I can not move or zoom the map, it's not responding at all. Other activities are working fine. I really have no clue where the problem might be.
Hope that someone can help me out?
Here is the sourcecode of my fragment that shows the MapView
public class FragmentAdvertlistMap extends Fragment {
com.google.android.gms.maps.MapView m;
GoogleMap mMap;
ArrayList<Advert> ads;
HashMap<Marker, String> myMarker;
public final LatLngBounds.Builder builder= new LatLngBounds.Builder();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
View inflatedView = inflater.inflate(R.layout.activity_advert_tab2, container, false);
m = (com.google.android.gms.maps.MapView)inflatedView.findViewById(R.id.map_tab);
m.onCreate(savedInstanceState);
myMarker = new HashMap<Marker, String>();
ads= AdvertListActivity.getAdverts();
setUpMapIfNeeded(inflatedView);
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent myIntent = new Intent(getActivity(), AdvertLocationActivity.class);
Advert putadvert = DefaultApplication.dbc.getAdvertForAdvertID(Integer.parseInt(myMarker.get(arg0)));
myIntent.putExtra("advert", putadvert);
startActivity(myIntent);
}
});
return inflatedView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((com.google.android.gms.maps.MapView) inflatedView.findViewById(R.id.map_tab)).getMap();
if (mMap != null) {
this.initMarker();
}
}
}
public void initMarker(){
for(int i=0;i<ads.size();i++){
Advert tempAd = ads.get(i);
LatLng tlalo = new LatLng(tempAd.mainLocation.latitude,tempAd.mainLocation.longitude);
builder.include(tlalo);
String address = "";
if(tempAd.mainLocation.contact_street != null){
address = address + tempAd.mainLocation.contact_street;
}
if(tempAd.mainLocation.contact_street_number != null){
address = address + " " + tempAd.mainLocation.contact_street_number;
}
Marker marker = mMap.addMarker(new MarkerOptions()
.position(tlalo)
.anchor(0.5f, 0.5f)
.title(tempAd.name)
.snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.androidpin)));
myMarker.put(marker,String.valueOf(tempAd.myid));
}
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
mMap.setOnCameraChangeListener(null);
}
});
}
#Override
public void onResume() {
super.onResume();
m.onResume();
}
#Override
public void onPause() {
super.onPause();
m.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
m.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
m.onLowMemory();
}
}
try add this in onCreateView()
container.removeAllViews();
I found it in another similar question to yours but I lost the original link of the answer...

Categories

Resources