How to show polylines on map [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I tried to show the polylines and it shows the correct line when I put it in onLocationResult.
However, I only want it to show polylines when the user clicks on the start button.
So I tried to put the code into onClickListener, the screen only displays the marker but not the lines.
Location mLastLocation;
LocationRequest mLocationRequest;
private SupportMapFragment mapFragment;
private FusedLocationProviderClient mFusedLocationClient;
private FirebaseAuth myAuth;
private FirebaseDatabase mDatabase;
private DatabaseReference myRef;
private Marker currentUserLocationMarker;
private ArrayList<LatLng> points; //added
Polyline line;
private Button btnStartRun;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googls_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);
points = new ArrayList<LatLng>();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
btnStartRun=findViewById(R.id.btnStartRun);
btnStartRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
points.add(latLng);//add points to the array
redrawLine();
myAuth=FirebaseAuth.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("OnlineUsers");//.child("OnlineUser");
DatabaseReference currentUserDB=mDatabase.child(myAuth.getCurrentUser().getUid());
currentUserDB.child("CurrentLatitude").setValue(mLastLocation.getLatitude());
currentUserDB.child("CurrentLongitude").setValue(mLastLocation.getLongitude());
}
});
}
Here is my onLocationResult
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
mLastLocation = location;
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
};
Here is my redrawline()
private void redrawLine(){
mMap.clear(); //clears all Markers and Polylines
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);//set the colour and width of the polyline
for (int i = 0; i < points.size(); i++) {
LatLng point = points.get(i);
options.add(point);
}
addMarker(); //add Marker in current position
line = mMap.addPolyline(options); //add Polyline
}
Thank you.

You are only adding to points on the button click, but that is incorrect. You should be adding to points every time you get an onLocationChanged (or perhaps your location callback), otherwise, you don't have any line to draw.
Your onLocationChanged (or callback) should call the redrawLine method every time.
Your redrawLine method should have a flag, such as hasStarted. If hasStarted = false, then clear the map, but don't draw the line. If hasStarted = true, then clear the map and DO draw the line.
In the onClick listener, simply set hasStarted = true (or, if you want it to be a toggle, say hasStarted = !hasStarted).

Related

moveCamera() uses wrong location data on Android

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));

Firebase database retrieve datas

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));

changing getMap to GetMapAsync

I am trying to create an interactive infoWindow based on one of the answers from Stack Overflow.
However, I am getting an error with getMap() used in the code. Although I've tried with getMapAsync(), I'm unable to resolve the problem. Please help me. If any new code is available for an interactive infowindow with a button, then please share the code.
public class MainActivity extends AppCompatActivity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton1, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener;
static final LatLng latlng1 = new LatLng(28.5355, 77.3910);
static final LatLng latlng2 = new LatLng(28.6208768, 77.3726377);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap googleMap = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(googleMap, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.custom_infowindow, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.nameTxt);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.addressTxt);
this.infoButton1 = (Button)infoWindow.findViewById(R.id.btnOne);
this.infoButton2 = (Button)infoWindow.findViewById(R.id.btnTwo);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton1, getResources().getDrawable(R.drawable.btn_bg), getResources().getDrawable(R.drawable.btn_bg)){
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, "click on button 1", Toast.LENGTH_SHORT).show();
}
};
this.infoButton1.setOnTouchListener(infoButtonListener);
infoButtonListener = new OnInfoWindowElemTouchListener(infoButton2, getResources().getDrawable(R.drawable.btn_bg),getResources().getDrawable(R.drawable.btn_bg)){
#Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(getApplicationContext(), "click on button 2", Toast.LENGTH_LONG).show();
}
};
infoButton2.setOnTouchListener(infoButtonListener);
/*infoWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click on infowindow", Toast.LENGTH_LONG).show();
}
});*/
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoSnippet.setText(marker.getTitle());
infoTitle.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
googleMap.addMarker(new MarkerOptions()
.position(latlng1)
.title("Source")
.snippet("Comapny Name")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions()
.position(latlng2)
.title("Destination")
.snippet("AmisunXXXXXX")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng1, 10));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
The error is coming because Google has removed getMap(), but I dont know the alternative solution for this.
UPDATE
Define private GoogleMap gMapand implement OnMapReadyCallback in your main Activity and implement onMapReady method
in onMapReady you should write this line
gMap = googleMap, then you can do what you want in onMapReady
getting current location
custom setting for your map
and ...
now it's time to use this lines in your OnCreate method
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
it should solve your problem, hope it helped you

How else can you make a variable in a class with Google Maps not a null? [duplicate]

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.

Google maps api v2 show all markers title always without any click

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();
}
}
}

Categories

Resources