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));
Related
I would like to make the map auto-focus to the current location and I've obtained the location via Location Kit.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
Now, I was trying to set the latitude and longitude of the camera in OnMapReady() function, but how to retrieve them?
#Override
public void onMapReady(HuaweiMap huaweiMap) {
float zoom = 12.0f;
LatLng latLng = new LatLng(***mLat***, ***mLong***);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
.
.
.
}
I really need your assistance!!
Update
There is a official demo show how to realize this:
use location kit to get the current location
use map kit to show current location point in map
You can try to use the function moveCamera or animateCamera to make the map move to the location you want :
#Override
public void onMapReady(HuaweiMap huaweiMap) {
float zoom = 12.0f;
LatLng latLng = new LatLng(***mLat***, ***mLong***);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
huaweiMap.moveCamera(cameraUpdate);
}
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).
I am trying for interactive infoWindow with one of the answer of stack overflow.
link is given below:
interactive infowindow
but i am getting error with getMap() used in the code. although I tried with getMapAsync but unable to resolve the problem. please help me asap.If any new code available for interactive infowindow with button then please share the code.
public class MainActivity extends Activity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton;
private OnInfoWindowElemTouchListener infoButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap map = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(map, 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.info_window, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button)infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.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
map.addMarker(new MarkerOptions()
.title("Prague")
.snippet("Czech Republic")
.position(new LatLng(50.08, 14.43)));
map.addMarker(new MarkerOptions()
.title("Paris")
.snippet("France")
.position(new LatLng(48.86,2.33)));
map.addMarker(new MarkerOptions()
.title("London")
.snippet("United Kingdom")
.position(new LatLng(51.51,-0.1)));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
error is coming because of google has removed getMap but dont know the alternative solution for this.
Error:(149, 42) error: cannot find symbol method getMap()
Your Existing Code is:
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final GoogleMap map = mapFragment.getMap();
Try this instead of that:
MapFragment mapFragment; // declare in global scope
GoogleMap googleMap; // declare in global scope
Put this code in OnCreate method:
mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(false); // false to disable
googleMap.setOnMarkerClickListener(onMarkerClick);
googleMap.setOnInfoWindowClickListener(onInfoWindowClick);
googleMap.getUiSettings().setZoomControlsEnabled(true);// Display Zoom Controls
googleMap.setMyLocationEnabled(true);// Display My Location Control
}
});
}
for converting pixels into DP use this:
public int getPixelsFromDp(int px){
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
Use getMapAsync in your onCreatView() method
((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map))
.getMapAsync(this)
Also imeplement the OnMapReadyCallback interface, and override it's method
In method onMapReady() which belongs to onMapReadyCallback interface do all the operations with your map you need. It will look like after your manipulations next
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// some action with our map
mMap.addMarker(new MarkerOptions().position(randomPosition).title("Random Title"));
mMap.addMarker(new MarkerOptions().position(antoherRandomPosition).title("Another RND Title"));
// some processes with db
DataBaseMapFragment database = new DataBaseMapFragment(dbHelper, mMap);
database.createBD();
// permission to check, if gps access is granted
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
//another actions with map
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camera, 13));
mMap.setBuildingsEnabled(true);
mMap.setOnMapLongClickListener(this);
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
mMap.setOnMarkerClickListener(this);
reffering Google documentation and guide.
Check it to learn more about maps in android and to be clear about
The getMap() function replaced from getMapAsync() more here
https://developers.google.com/android/reference/com/google/android/gms/maps/package-summary
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();
}
}
}