I have this map and I want to set the location to the lat , lon that I receive in the Intent extras.How can I do it?
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private SupportMapFragment mMapFragment;
private GoogleMap mGoogleMap;
private String lat;
private String lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
lat=getIntent().getStringExtra("lat");
lon=getIntent().getStringExtra("lon");
mMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap=googleMap;
}
}
put this code in onMapReady
double lat = location.getLatitude();
double lng= location.getLongitude();
// set up marker and add
googleMap.addMarker(new MarkerOptions().position(new LatLng(lat , lng))
.title("Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
// move camera to it
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 8));
always do all map-related features like drawing polygons, adding markers, moving camera etc. after onMapReady call, so when googleMap won't be null. And remember that even if it gets called every time for you - in some circulumstances it may not get fired on some device and every googleMap.someMethod() call (e.g. under onClick) will throw you NullPointerException. be prepared for that
Related
I am using Algolia's InstantSearch Android library.
This is my Query:
searcher.setQuery(new Query().setAroundLatLngViaIP(true).setAroundRadius(5000)).
But when I move the map, the markers stay in place. How can I display the new markers on the map when I move the map location view?
So basically you want to listen to the map changes and every time the user is dragging the map and reload the results? Here's what you should do:
public class AwesomeCameraActivity extends FragmentActivity implements
OnCameraIdleListener,
OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_camera);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setOnCameraIdleListener(this);
// Show the initial position
mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(YOUR_LATITUDE, YOUR_LONGITUDE), 10));
}
#Override
public void onCameraIdle() {
// The camera / map stopped moving, now you can fetch the center of the map
GeoPoint center = mMap.getProjection().fromPixels(mMap.getHeight() / 2, mMap.getWidth() / 2);
double centerLat = (double)center.getLatitudeE6() / (double)1E6;
double centerLng = (double)center.getLongitudeE6() / (double)1E6;
// Now fire a new search with the new latitude and longitude
searcher.setQuery(new Query().setAroundLatLng(new AbstractQuery.LatLng(centerLat, centerLng)).setAroundRadius(5000))
}
}
I have this EventActivity where I have a map with a marker:
public class EventActivity extends AppCompatActivity implements OnMapReadyCallback {
private double latitude;
private double longitude;
private GoogleMap eventMap;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
// Declares map fragment.
SupportMapFragment eventMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.activity_event_map);
eventMapFragment.getMapAsync(this);
// Gets latitude and longitude values from database.
// (things happen here and I get the values correctly)
latitude = 12.4567785
longitude = 25.7773665
}
#Override
public void onMapReady(GoogleMap googleMap) {
eventMap = googleMap;
// Sets map position.
LatLng position = new LatLng(latitude, longitude);
eventMap.addMarker(new MarkerOptions().position(position));
eventMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
}
On the OnCreate() I get the pair of double values correctly. I can even make a toast and it shows them.
The problem is, when I want to set them as the position for the marker of my map on the OnMapReady() it gets nothing or null.
How can I properly pass the values from OnCreate() to OnMapReady()?
EDIT: I'm using Firebase as my database.
Perhaps initialize the map fragment after assigning the lat/long values as such:
public class EventActivity extends AppCompatActivity implements OnMapReadyCallback {
private double latitude;
private double longitude;
private GoogleMap eventMap;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
// Gets latitude and longitude values from database.
// (things happen here and I get the values correctly)
latitude = 12.4567785
longitude = 25.7773665
// Declares map fragment.
SupportMapFragment eventMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.activity_event_map);
eventMapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
eventMap = googleMap;
// Sets map position.
LatLng position = new LatLng(latitude, longitude);
eventMap.addMarker(new MarkerOptions().position(position));
eventMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
}
I needed to solve a similar issue and currently have this solution working in my app. I wanted to add a new polyline from my location to the marker in question so wanted setOnMarkerListener to have access to my location. Here is how I solved it:
Step 1.
I created two global doubles as follows:
private Double myLatitude = -33.865143;
private Double myLongitude = 151.209900;
I gave them a default value of Sydney to avoid any NullPointerException error as I am adding polylines to an array of polylines.
Step 2.
In my onLocationChanged method I updated the values:
#Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
....
Now in Step 3 I wanted to create a new line from mylocation to the selected marker so used the following code:
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
areaText.setText(marker.getTitle());
distanceText.setText("0 Meters");
markerLatitude = marker.getPosition().latitude;
markerLongitude = marker.getPosition().longitude;
lines.add(mMap.addPolyline(new PolylineOptions()
.add(new LatLng(myLatitude, myLongitude),
new LatLng(marker.getPosition().latitude, marker.getPosition().longitude))
.width(10)
.color(Color.RED)));
if (lines.size() > 1)
lines.remove((lines.size()-1));
return true;
}
});
Hope this helps someone with the same issue.
First, I plot a Marker like this:
public void addMarker(String title,String lat,String Lng,int id,String address,int f)
{
marker= mMap.addMarker(new MarkerOptions().snippet(title)
.title(title+", "+address)
.position(new LatLng(Double.valueOf(lat), Double.valueOf(Lng)))
.icon(BitmapDescriptorFactory.fromResource(id)));
LatLng coordinate = new LatLng(Double.valueOf(lat), Double.valueOf(Lng));
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 10);
mMap.animateCamera(yourLocation);
mMarkerArray.add(marker);
}
After that I am trying to replace the Marker with another icon when ever I reached at any existing Location
#Override
public void onLocationChanged(Location location)
{
Log.d("latitude_main", "onlocation???");
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.e("latitude_main", "latitude--" + latitude+"longitude="+longitude);
current_lat= String.valueOf(latitude);
current_lng= String.valueOf(longitude);
Log.e("latitude_main","size-=="+salesmanlocationArrayList.size() );
for(int i=0;i<salesmanlocationArrayList.size();i++)
{
if(salesmanlocation.getLati().equals("12.9165757") && salesmanlocation.getLongi().equals("77.6101163"))
{
mMap.addMarker(new MarkerOptions()
.snippet(""+i).title(salesmanlocation.getFirm_name()+", "+salesmanlocation.getAddress())
.position(new LatLng(Double.valueOf(salesmanlocation.getLati().toString()), Double.valueOf(salesmanlocation.getLongi().toString())))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.event_events_select)));
}
mapFragment.getMapAsync(this);
}
}
I want to remove the marker from the map when the user visits that location.
You can simply define one OnMyLocationChangeListener class that performs your tasks, and set it on your GoogleMap instance, this way you can use it whenever you want in your application.
Step 1 - define your listener
public class MyMarkerLocationListener implements GoogleMap.OnMyLocationChangeListener {
List<Marker> markerList;
int MY_DISTANCE;
GoogleMap mMap;
public MyMarkerLocationListener(List<Marker> markerList, int meters, GoogleMap mMap)
{
this.markerList = markerList;
this.MY_DISTANCE = meters;
this.mMap = mMap;
}
#Override
public void onMyLocationChange(Location location) {
// your code/logic
//...
Location myNewLocation = location;
Location someMarkerLocation = new Location("some location");
//for each marker on your list
//check if you are close to it
for (Marker m : markerList) {
LatLng markerPosition = m.getPosition();
someMarkerLocation.setLatitude(markerPosition.latitude);
someMarkerLocation.setLongitude(markerPosition.longitude);
if (myNewLocation.distanceTo(someMarkerLocation) < MY_DISTANCE) {
//remove marker
m.remove();
//or if you still want to use it later
//m.setVisible(false);
// add your new marker
//mMap.addMarker(new MarkerOptions().icon()....);
}
}
}
}
After defining your class you just set the listener on your map on your fragment or activity code =)
Step 2 - instanciate the listener and set it
MyMarkerLocationListener myListener = new MyMarkerLocationListener(mMarkerArray, 100, mMap);
mMap.setOnMyLocationChangeListener(myListener);
UPDATE to answer your question in the comments:
You should initialize mMap before using it, take a look at this piece of code from this Stackoverflow question
public class MapPane extends Activity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
map.setTrafficEnabled(true);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
}
don't forget your activity should implement the OnMapReadyCallback interface so the onMapReady method is called
you can use the map only after it is ready
Hope this helps!
I new in coding google map,
my question is how i control the user gestur drag , zoom in and zoom out.
because my code always back to the current location of user when i zoomin/out, nad when i drag/ scroll up, down, left, right. always back to the current possition .
its my code for current loc user
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
}
};
You can use a boolean to move the camera only the first time:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
private Marker mMarker;
private boolean firstTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if (firstTime) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
firstTime = false;
}
}
}
NOTE: Take into account that this example uses GoogleMap.OnMyLocationChangeListener only because that is the method that you are using in your question, but it's deprecated and you must use the FusedLocationProviderApi according to the documentation:
public final void setOnMyLocationChangeListener
(GoogleMap.OnMyLocationChangeListener listener)
This method was deprecated. use
com.google.android.gms.location.FusedLocationProviderApi instead.
FusedLocationProviderApi provides improved location finding and power
usage and is used by the "My Location" blue dot. See the
MyLocationDemoActivity in the sample applications folder for example
example code, or the Location Developer Guide.
I am trying to add a marker all depending on what activity the user is on. For example, if the user is in the location1 activity and clicks the button to open maps, it should open Google Maps with a marker at where location1 is. Alternatively, if the user is in the location2 activity and clicks the button to open maps, it should open Google Maps with a marker at where location 2 is.
I have it working when they click on one activity, it brings them to Google Maps and has a marker at where that location is. I have simply tried to copy the code and paste it below with the edited names in it, but if I click a different activity to go to maps, it brings me to the same marker as previously.
My Code for GoogleMapsActivity is below:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Add a marker at the Oval and move the camera
LatLng oval = new LatLng(53.3484013, -6.2605243);
mMap.addMarker(new MarkerOptions().position(oval).title("Oval Pub"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(oval));
/*
// Add a marker at Diceys and move the camera
LatLng diceys = new LatLng(53.3358088,-6.2636688);
mMap.addMarker(new MarkerOptions().position(diceys).title("Diceys Nightclub"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(diceys));
*/
}
public void changeType(View view)
{
if(mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL)
{
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}}
As you can see, I have commented out the code where I have tried adding a marker for a different location, but it seems to bring me to the same location as above.
Not sure if this is something simple or not as I am new to Google Maps in Android.
Any help would be greatly appreciated.
Thank you.
ArrayList<MarkerData> markerArray = new ArrayList<MarkerData>();
for(int i = 0 ; i < markersArray.size() ; i++ ) {
createMarker(markersArray.get(i).getLatitude(), markersArray.get(i).getLongitude(), markersArray.get(i).getTitle(), markersArray.get(i).getSnippet(), markersArray.get(i).getIconResID());
}
....
protected void createMarker(double lat, double lon, String title, String snippet, int iconResID) {
return googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet);
.icon(BitmapDescriptorFactory.fromResource(iconResID)));
}
Tying it all together:
ArrayList<LatLng> locations = new ArrayList();
locations.add(new LatLng(30.243442, -1.432320));
locations.add(new LatLng(... , ...));
.
.
.
for(LatLng location : locations){
mMap.addMarker(new MarkerOptions()
.position(location)
.title(...)
}
In First Location activity:
Intent i = new Intent(FirstLocationActivity.this, MapsActivity.class);
String keyLatitude = ""; //enter the value
String keyLongitude = ""; //enter the value
i.putExtra("latitude", keyLatitude );
i.putExtra("longitude", keyLongitude );
startActivity(i);
similarly do the same for activity two location, add its corresponding latitude and longitude in extra
In your mapsActivity,
String latitude="";
String longitude ="";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
Bundle bundle = getIntent().getExtras();
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Add a marker at the Oval and move the camera
LatLng oval = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(oval).title("Oval Pub"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(oval));
}