How to make the human marker move on the map? - java

I have a marker humanMarker on the map. How to make it move when the user is moving?
private Marker humanMarker;
humanMarker = map.addMarker(new MarkerOptions()
.position(new LatLng(mLocation.getLatitude(), mLocation.getLongitude()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.human)));

Try to override the onLocationChanged method. humanMarker will move when the location of the user is changed.
#Override
public void onLocationChanged(Location location) {
// Update current location of the marker
humanMarker.setPosition(new LatLng(location.getLatitude(), location.getLongitude()));
}

Related

android null pointer exception when adding custom marker [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When i am trying to add custom marker it throws NullPointerException,
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
Here is my map activity
public class GoogleMapActivity extends AppCompatActivity
{
double latitude, longitude;
GoogleMap map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void getCurrentLocation()
{
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
moveMap();
}
}
private void moveMap()
{
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title("Current Location"));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.googlemap, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
getCurrentLocation();
moveMap();
}
return super.onOptionsItemSelected(item);
}
}
How can i fix this problem?
private void getCurrentLocation()
{
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
moveMap(location);
}
}
private void moveMap(Location location)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title("Current Location"));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
You don't have latitude and longitude in the scope of function you are trying to access in.
and you are also not implementing onMapReady() function. Seems like a lot of things are broken.
Example: https://github.com/googlemaps/android-samples/blob/master/tutorials/MapWithMarker/app/src/main/java/com/example/mapwithmarker/MapsMarkerActivity.java
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map when it's available.
* The API invokes this callback 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 receives a prompt to install
* Play services inside the SupportMapFragment. The API invokes this method after the user has
* installed Google Play services and returned to the app.
*/
#Override
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));
}
}

Google Maps: Current Location Marker (Period updates for GMaps)

So I've been able to get periodic updates of my current location through the developer android page, making your app location aware. Now, whenever my location changes, I am able to get the latitude and longitude of that location. However, who do i implement this with Google Maps?
This line below implements a button on my map that finds my current location and places a blue dot/marker on it (does not receive periodic updates)
mMap.setMyLocationEnabled(true);
What should I put in my onLocationChanged() event in order for the blue dot to be updated with the new lat and long?
The blue dot and the precision circle are automatically managed by the map and you can't update it or change it's symbology. In fact, it's managed automatically using it's own LocationProvider so it gets the best location resolution available (you don't need to write code to update it, just enable it using mMap.setMyLocationEnabled(true);).
If you want to mock it's behaviour you can write something like this (you should disable the my location layer doing mMap.setMyLocationEnabled(false);):
private BitmapDescriptor markerDescriptor;
private int accuracyStrokeColor = Color.argb(255, 130, 182, 228);
private int accuracyFillColor = Color.argb(100, 130, 182, 228);
private Marker positionMarker;
private Circle accuracyCircle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
markerDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.yourmarkericon);
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float accuracy = location.getAccuracy();
if (positionMarker != null) {
positionMarker.remove();
}
final MarkerOptions positionMarkerOptions = new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(markerDescriptor)
.anchor(0.5f, 0.5f);
positionMarker = mMap.addMarker(positionMarkerOptions);
if (accuracyCircle != null) {
accuracyCircle.remove();
}
final CircleOptions accuracyCircleOptions = new CircleOptions()
.center(new LatLng(latitude, longitude))
.radius(accuracy)
.fillColor(accuracyFillColor)
.strokeColor(accuracyStrokeColor)
.strokeWidth(2.0f);
accuracyCircle = mMap.addCircle(accuracyCircleOptions);
}
mMap.setMyLocationEnabled(true);
this is simple trick for blue marker of current location and did the trick for me.

Drawing polylines between two points using an Arraylist of LatLng

I want to draw polylines between two points with using polylineoptions.addAll sending a parameter of ArrayList<LatLng>, but it doesn't show me the result.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private ArrayList<LatLng> arrayPoints = new ArrayList<>();
PolylineOptions polylineOptions=new PolylineOptions();
#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.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
LatLng point=new LatLng(-35,151);
LatLng point2=new LatLng(-40,151);
polylineOptions.color(Color.RED);
polylineOptions.width(3);
arrayPoints.add(point);
arrayPoints.add(point2);
polylineOptions.addAll(arrayPoints);
}
/**
* 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)
{
}
}
Looks like you're not adding the polyline to the map
mMap.addPolyline(polylineOptions)

How to tell if a Marker is in a Polygon googleMap v2

I've got a Google Map with Polygons, I've got everything to work except this last part which is detect if a Marker is already inside a Polygon.The current situation is when I touch a Polygon it will add the Marker"which is correct" but if I touch the Polygon in a different spot it will remove the Marker and add a new one. What I want to happen is if a Marker is already within those points don't add a new one. My code is below any help would be appreciate.
public void onMapClick(LatLng point) {
for (int j = 0; j < arrPolygons.size(); j++) {
if (isPointInPolygon(point, arrPolygons.get(j).getPoints())) {
if (marker != null) {
marker.remove();
marker = null;
Log.v("Marker", "Removing Marker");
}else{
marker = googleMap.addMarker(new MarkerOptions()
.position(point)
.title("test")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Log.v("Marker", "ADDing Marker");
}
}
}
Any help would be appreciated.
The easiest way to do this would be using the Google Maps Android API Utility Library, which contains the PolyUtil class.
First import the library by adding the current version to your build.gradle, currently 0.3.4
for example:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services-maps:7.3.0'
compile 'com.google.maps.android:android-maps-utils:0.3.4'
}
For this simple example we'll assume the Map Activity class definition and member variables look like this, and only one Polygon defined in polygonList:
import com.google.maps.android.PolyUtil;
//other imports.....
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Marker marker;
List<LatLng> polygonList = new ArrayList<LatLng>();
//.............
You would then set up your GoogleMap.OnMapClickListener like this in order to only add one Marker inside the Polygon.:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
if (PolyUtil.containsLocation(point, polygonList, false)) {
if (marker == null) {
//only add Marker if there is not one already inside the Polygon
marker = mMap.addMarker(new MarkerOptions()
.position(point)
.title("test")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Log.v("Marker", "ADDing Marker");
}
}
}
});
Multiple Polygons, Multiple Markers Solution:
In order to make it work with multiple Ploygons, you could use a POJO to store Polygon/Marker pairs:
public class PolyMarkerObject{
Polygon polygon;
Marker marker;
}
Then define a new member variable polyMarkerList:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
List<PolyMarkerObject> polyMarkerList = new ArrayList<>();
//.............
Add each Polygon to the list when drawing it:
List<LatLng> newPolygon = new ArrayList<>();
//set up the points in the Polygon.......
Polygon p = mMap.addPolygon(new PolygonOptions()
.addAll(newPolygon)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
PolyMarkerObject newPolyMarkerObj = new PolyMarkerObject();
newPolyMarkerObj.polygon = p;
polyMarkerList.add(newPolyMarkerObj);
Then cycle through the list on each Map click to see whether the current Ploygon already has a Marker. If it does not have a Marker already, then remove any Marker already placed in a different Polygon, and create one in the current Polygon:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
for (PolyMarkerObject pmObj : polyMarkerList) {
//only add Marker if there is not one already inside the Polygon
if (PolyUtil.containsLocation(point, pmObj.polygon.getPoints(), false)) {
if (pmObj.marker == null) {
//Add Marker to current Polygon
Marker newMarker = mMap.addMarker(new MarkerOptions()
.position(point)
.title("test")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
pmObj.marker = newMarker;
Log.v("Marker", "ADDing Marker");
break;
}
}
}
}
});
Multiple Polygons, One Marker Solution:
In this case, you just need one Marker reference, and a list of Polygons:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Marker marker;
List<Polygon> polyList = new ArrayList<>();
//................
Add the Polygon to the list when it's added to the Map:
List<LatLng> newPolygon = new ArrayList<>();
//set up the points in the Polygon.......
Polygon p = mMap.addPolygon(new PolygonOptions()
.addAll(newPolygon)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
polyList.add(p);
Then, in the Map click listener, you have two cases, one for if the Marker reference is null (no Marker added yet), and one for if the Marker is in a different Polygon. If the Marker is in the current Polygon already, it will not be moved.
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
for (Polygon pObj : polyList) {
//find Polygon user tapped inside of
if (PolyUtil.containsLocation(point, pObj.getPoints(), false)) {
//first case, no Marker
if (marker == null) {
//Add Marker to current Polygon
marker = mMap.addMarker(new MarkerOptions()
.position(point)
.title("test")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Log.v("Marker", "ADDing first Marker");
break;
}
else if (!PolyUtil.containsLocation(marker.getPosition(), pObj.getPoints(), false)) {
//Marker exists already in a different Polygon
//remove Marker from previous Polygon
marker.remove();
//Add Marker to current Polygon
marker = mMap.addMarker(new MarkerOptions()
.position(point)
.title("test")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Log.v("Marker", "Moving Marker to new Polygon");
break;
}
}
}
}
});

display all markers on map

I want to display all the markers on Google map in my application, with info window and when click on the info window it should take me to another activity for description.
I am able to show all the marker on the map, but when i click on the info window it takes me to the last item stored in my database.. What i am doing wrong ?
Here is my code:
Cursor c1 = newDB.rawQuery("SELECT name,latitude,longtude,category_type FROM facilities " , null);
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
double latitude =c1.getDouble(c1.getColumnIndex("latitude"));
double longitude = c1.getDouble(c1.getColumnIndex("longtude"));
String cat =c1.getString(c1.getColumnIndex("category_type"));
nnn = c1.getString(c1.getColumnIndex("name"));
GeoPoint p = new GeoPoint(
(int)(latitude *1E6 ),
(int)(longitude *1E6 ));
//Write a code to display this point on google-map
// map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(nnn));
if ("Monuments".equals(cat))
{
Marker melbourne = map.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(nnn)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.palace)));
onInfoWindowClick(melbourne);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(NearbyActivity.this,Description.class);
intent.putExtra("id", nnn);
startActivity(intent);
} });
}
It takes the value of the title(the variable nnn) on the info window right, only when i click on the info window it makes the variable (nnn) the last item stored in database. I need help for that Please.
Thanks in advance :)

Categories