I need to use the Latitude and Longitude I get on LocationChanged to show on MAP the position at the time, but I'm not sure how to pass it!
I've used Intent.putExtra but it brakes down my application, but i don't really know why (I still get the coords when I don't use "map.putExtra("Latlng", Local);") but adding it breaks my app, help please
//map is the name of the Intent of the google maps Activity
#Override
public void onLocationChanged(Location location) {
TextView coords=(TextView)findViewById(R.id.text_view_coords);
double latitude=location.getLatitude();
double longitude=location.getLongitude();
coords.setText("Latitude:"+Location.convert(latitude,Location.FORMAT_SECONDS)
+"\n" +
"Longitude:"+Location.convert(longitude,Location.FORMAT_SECONDS));
LatLng Local = new LatLng(latitude, longitude);
//Passar o Bundle referente ao LatLng criado anteriormente.
map.putExtra("Latlng", Local);
}
----------------------MapsActivity ---------------------
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
double lat;
double lng;
LatLng objLatLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
objLatLng=getIntent().getExtras().getParcelable("Latlng");
// 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;
//Recebendo do objeto LatLng as coordenadas em DOUBLE referentes a Latitude e a Longitude
lat = objLatLng.latitude;
lng = objLatLng.longitude;
//Referentes a marcação e setagem da posição atual na API do Google Maps
LatLng PosAtual = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(PosAtual).title("Sua posição atual!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(PosAtual));
}
}
The reason for this is that
LatLng Local = new LatLng(latitude, longitude);
is not parcelable and you got to convert this into some String using Gson and then pass it to bundle and convert it back to object using again Gson
or just pass lat long alone using
putExtra("lat",latitude)
putExtra("long),longitude)
try to pass it as separate like below
map.putExtra("latitude", latitude);
map.putExtra("longitude", longitude);
And on get on MapsActivity activity like below
double lat = getIntent().getDoubleExtra("latitude");
double lang = getIntent().getDoubleExtra("longitude");
or putParcelable method to attached LatLng Object to a Bundle
Bundle args = new Bundle();
args.putParcelable("Latlng", Local);
map.putExtra("bundle", args);
To get in MapActivity like
Bundle bundle = getIntent().getParcelableExtra("bundle");
LatLng objLatLng = bundle.getParcelable("Latlng");
Related
I hope you can help me. My current app is able to get my current location (via GPS). Now I add a marker to my current location which works perfect, but if I want to move my camera to the marker it doesn't work. The inputs for the moveCamera(positon); are the same as for addMarker(position);
here is my code:
//center is used when no location is available (Berlin)
final CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(52.5075389,13.5231758));
final CameraUpdate zoom = CameraUpdateFactory.zoomTo(14);
//get location from other activity
final Bundle extras = getIntent().getExtras();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng position = new LatLng(52.5075389,13.5231758);
if (extras != null) { //if location available
position = (LatLng)extras.getParcelable("location");
final CameraUpdate centerLocation = CameraUpdateFactory.newLatLng(position);
MarkerOptions markerOptions = new MarkerOptions().position(position).title(MARKER_TITLE).snippet(MARKER_SNIPPET);
googleMap.addMarker(markerOptions);
googleMap.getUiSettings().setMapToolbarEnabled(false); //hide auto created buttons
googleMap.moveCamera(centerLocation);
googleMap.animateCamera(zoom);
}
else{
//some other code here
}
My marker is at the correct position, but my centerLocation don't. Any suggestions?
thanks to the comments. here is my solution:
final float zoom = 14;
//rest of the code is unchaged
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, zoom));
Hi guys im very new with app development ,any ideas how im i able to store my Latitude and Longitude of my users positions with its names and plot in my google maps?
I used this code below and it is working fine it plot the multiple marker as expected , my problem is ,i have my datas from firebase data base please see images
2 users with positions :
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GoogleMap googleMap;
private MarkerOptions options = new MarkerOptions();
private ArrayList<LatLng> latlngs = new ArrayList<>();
private ArrayList<String> Names = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
latlngs.add(new LatLng(12.334343, 33.43434)); //some latitude and logitude value
latlngs.add(new LatLng(10.334343, 32.43434)); //some latitude and logitude value
Names.add("Name 1"); //some latitude and logitude value
Names.add("Name 2"); //some latitude and logitude value
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
for (LatLng point : latlngs) {
options.position(point);
options.title(String.valueOf(Names));
options.snippet("someDesc");
googleMap.addMarker(options);
}
}
}
The code below is used to fetch data from firebease:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Positions");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot chidSnap : dataSnapshot.getChildren()) {
System.out.println("id",""+ chidSnap.getKey()); //displays the key for the node
System.out.println("Latit",""+ chidSnap.child("Latitude").getValue());
System.out.println.v("Longitude",""+ chidSnap.child("Longitude").getValue()); //gives the value for given keyname
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
you get data from firbase database and store it in list you want to publish marker on map
you can use this Method
public ArrayList<MarkerOptions> publishMarker(GoogleMap googleMap, int recourceMarker) {
ArrayList<MarkerOptions> markerOption = new ArrayList<>();
for (LatLng point : latlngs) {
MarkerOptions markerOptions = new MarkerOptions().position(point);
markerOptions.icon(BitmapDescriptorFactory.fromResource(recourceMarker));
markerOption.add(markerOptions);
googleMap.addMarker(markerOptions).setTag(point);
googleMap.addMarker(markerOptions);
}
return markerOption;
}
then call method in on mapReady Method
ArrayList<MarkerOptions> markerOptions=publishMarker(mMap, R.drawable.map_marker);
if (markerOptions!=null&&markerOptions.size() > 0)this.mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(markerOptions.get(0).getPosition(), 15));
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a class with map, and took coordinates and title, from Firebase in String format, then put them into double, but can't place them to new LatLng? I understand, that problem is that googleMap = null, but re-tried all the ways to solve it. In this version of code, nullexception is disapearing, but marker is empty. Help please. It the last problem of my app..
public class Map_activity extends FragmentActivity implements OnMapReadyCallback{
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_activity);
// 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);
String value = getIntent().getExtras().getString("qwerty");
String xlat = getIntent().getExtras().getString("lat");
String xlon = getIntent().getExtras().getString("lon");
xlat.split(",");
xlon.split(",");
String [] latlong = {xlat, xlon};
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
if (googleMap != null){
LatLng location = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(location).title(value));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(location));}
}
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
}
onCreate is getting called before onMapReady. If the map is not ready, then the only value googleMap can be is null.
The only solution is to move the code that needs googleMap out of onCreate and put it somewhere else.
I'm implementing android Mapview with Custom marker. I'm using picasso to load image into marker view. And when i launch the app at the first time, it shows me all the markers, but only one marker that has loaded from database with picasso, the other markers are not loaded from database, they only show me the default maps marker pin. But when i go to the previous activity and go back into MapsActivity, it shows me all the markers that loaded from database with picasso.
Here's my PicassoMarker class
public class PicassoMarker implements Target {
Marker mMarker;
PicassoMarker(Marker marker) {
mMarker = marker;
}
#Override
public int hashCode() {
return mMarker.hashCode();
}
#Override
public boolean equals(Object o) {
if(o instanceof PicassoMarker) {
Marker marker = ((PicassoMarker) o).mMarker;
return mMarker.equals(marker);
} else {
return false;
}
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
//mMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.here));
}
}
Here's the method in MapsActivity
public void plotMarkers(ArrayList<MyMarker> markers) {
if(markers.size() > 0) {
for (MyMarker myMarker : markers)
{
markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));
location_marker = mMap.addMarker(markerOption);
target = new PicassoMarker(location_marker);
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(84, 125).into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if(i.getBooleanExtra("maps", true)) {
buttonNavigasi.setVisibility(View.VISIBLE);
location_marker.setTitle(i.getStringExtra("nama"));
dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(dest, 16));
}
else {
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
What's going wrong here?
Thanks.
Okay, so I managed to reproduce what you are experiencing and found what was causing your problem. In the code you provided, notice this line in MapsActivity:
target = new PicassoMarker(location_marker);
I presumed that you are using a global single variable for target. I added some logs and managed to see that the only Marker that gets the image loaded using Picasso is the last Marker in the for loop.
The reason is because, every time you enter the loop, the value of target changes to the newer PicassoMarker that you have, making the onBitmapLoaded of the previous PicassoMarker you have useless, since it no longer has a target. :(
So what I did is, I just added a List<Target> variable (make sure you don't forget to initialize it) to store the instances of the targets. In the line where that I specified earlier, I just added the code to store the value of the target to the list, like so:
Target target = new PicassoMarker(location_marker);
targets.add(target);
Tested it on my emulator and it loads the images to all the Markers.
EDIT
Here is the Activity code I used to reproduce your error and then modified it to make it work:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Intent i;
MarkerOptions markerOption;
List<Target> targets;
HashMap<Marker, MyMarker> mMarkersHashMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMarkersHashMap = new HashMap<>();
targets = new ArrayList<>();
// 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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
ArrayList<MyMarker> markers = new ArrayList<MyMarker>();
MyMarker m1 = new MyMarker(new LatLng(-34, 151.1), "https://developer.chrome.com/extensions/examples/api/idle/idle_simple/sample-128.png");
MyMarker m2 = new MyMarker(new LatLng(-34, 151.2), "https://developer.chrome.com/extensions/examples/api/idle/idle_simple/sample-128.png");
MyMarker m3 = new MyMarker(new LatLng(-34, 151.3), "https://developer.chrome.com/extensions/examples/api/idle/idle_simple/sample-128.png");
markers.add(m1);
markers.add(m2);
markers.add(m3);
plotMarkers(markers);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Log.d(MapsActivity.class.getSimpleName(), "MARKER Longitude: " + marker.getPosition().longitude);
return false;
}
});
}
public void plotMarkers(ArrayList<MyMarker> markers) {
if (markers.size() > 0) {
for (MyMarker myMarker : markers) {
markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));
Marker location_marker = mMap.addMarker(markerOption);
Target target = new PicassoMarker(location_marker);
targets.add(target);
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(84, 125).into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if (i.getBooleanExtra("maps", true)) {
// buttonNavigasi.setVisibility(View.VISIBLE);
location_marker.setTitle(i.getStringExtra("nama"));
LatLng dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(dest, 8f));
} else {
Log.d(MapsActivity.class.getSimpleName(), "In else{}");
// mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
}
I need that in my Map-application Google map markers title always will be shown without any user click. I want that this title even will not be possible hide.
Of course I searched online, and I found this: marker.showInfoWindow(); but it is not working because I have near to 30 markers and I need that all of them will be shown all the time (I guess marker.showInfoWindow(); working just when there is one marker).
............................................................................
(And I would like to know how to do that when map activity will start it will not show whole world from far, but from specific country. I mean already zoomed to this country.)
public class Map extends Activity {
static LatLng Sapphire = new LatLng(41.085078, 29.006100);
static LatLng Metrocity = new LatLng(41.076138, 29.010518);
static LatLng Istinye = new LatLng(41.114247, 29.058924);
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions().position(Sapphire).title("Istanbul Sapphire").snippet("Levent")); marker.showInfoWindow();
Marker marker1 = googleMap.addMarker(new MarkerOptions().position(Metrocity).title("Metrocity").snippet("Levent")); marker1.showInfoWindow();
Marker marker2 = googleMap.addMarker(new MarkerOptions().position(Istinye).title("Istinye Park").snippet("Istinye/ Pınar Mh.")); marker2.showInfoWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
}