FragmentActivity - Zoom to show streets - java

I'm having some issues using FragmentActivity and SupportMapFragment. The map's zoom is all wonky.
Here's the code:
public class GoogleMapActivity extends FragmentActivity{
Double longitude, latitude;
static LatLng koordinate;
GoogleMap supportMap;
String title, address;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googlemaps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMap = fm.getMap();
longitude = 13.597651720046997;
latitude = 45.22456639103469;
title = "Turistička zajednica Općine Vrsar";
address = "ul. Rade Končara 46";
koordinate = new LatLng(longitude, latitude);
Marker marker = supportMap.addMarker(new MarkerOptions().position(koordinate).title(title).snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_star)));
//supportMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
supportMap.moveCamera(CameraUpdateFactory.newLatLngZoom(koordinate, 15));
supportMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}}
For some reason, I get following thing in google maps, which is not zoomed enough:
http://imageshack.us/f/812/3yl.png/
When I click on the zoom, the map goes into this state:
http://imageshack.us/f/825/k8np.png/
I need the maps to zoom enough so that the street names are shown.This works just fine in my previous application, but I used regular MapFragment there. For this app, I need SupportMapFragment. Maybe that's causing this issue?

Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
OR
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
the maximum zoom allowed is 17 i guess.
i hope this must work...

Related

Google maps Markers Titles Showing is full list

Im working with google maps project now and im fetching my data from firebase ,im able to plot multiple markers with the help of all the kind developers in this site, one thing is when plotting those markers my markers title are the same , the "same" means that all my markers have the same Title please see my image
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<>();
String Lat ,Lon,Names1;
double latitude , longitude;
#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);
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(chidSnap.getKey()); //displays the key for the node
// System.out.println(chidSnap.child("Latitude").getValue());
// System.out.println( chidSnap.child("Longitude").getValue()); //gives the value for given keyname
//some latitude and logitude value
// System.out.println(latlngs); //gives the value for given keyname
Lat = String.valueOf(chidSnap.child("Latitude").getValue());
Lon = String.valueOf(chidSnap.child("Longitude").getValue());
Names1 = String.valueOf(chidSnap.getKey());
latitude= Double.parseDouble(Lat);
longitude= Double.parseDouble(Lon);
latlngs.add(new LatLng(latitude, longitude));
Names.add(Names1);
}
if(mMap != null) {
for (LatLng point : latlngs) {
options.position(point);
options.title(String.valueOf(Names));
options.snippet("someDesc");
mMap.addMarker(options);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// System.out.println(Names);
}
/**
* 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;
for (LatLng point : latlngs) {
options.position(point);
options.title(String.valueOf(Names));
options.snippet("someDesc");
googleMap.addMarker(options);
}
}
}
My MapsActivity above. What im expecting is one marker should be named to Lex B05 , and the other user should be amanda thank in advance for your help!..
That because you are passing same arrayList Names to all marker, Try below code while adding marker
for (int i=0;i< latlngs.size();i++) {
LatLng point=latlngs.get(i);
options.position(point);
options.title(Names.get(i));
options.snippet("someDesc");
mMap.addMarker(options);
}
Hope this will help!!

How to read a txt file in android studio?

I have a text file speedVan.txt in my assets folder in android studio which stores coordinates, However when I run it the markers do not appear on the map. My code is below, thank you.
This is the content of the text file, there are no spaces between the text lines:
52.2651 -9.7112 52.2791 -9.7024
52.2800 -9.7675 52.2746 -9.8096
52.1407 -10.1748 52.1296 -10.2493
52.0724 -9.5753 52.1005 -9.6231
52.1021 -9.6276 52.1065 -9.6425
52.0812 -9.2470 52.0542 -9.3850
52.1134 -9.5169 52.1437 -9.5543
52.4096 -9.5167 52.4208 -9.5078
52.4428 -9.4105 52.4491 -9.4474
This is my activity:
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;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("speedVan.txt")));
String line;
//Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] ar1 = line.split(" ");
double startLat = Double.parseDouble(ar1[0]);
double startLong = Double.parseDouble(ar1[1]);
double endLat = Double.parseDouble(ar1[2]);
double endLong = Double.parseDouble(ar1[3]);
LatLng start = new LatLng(startLat, startLong);
LatLng end = new LatLng(endLat, endLong);
mMap.addMarker(new MarkerOptions().position(start).title(""));
mMap.addMarker(new MarkerOptions().position(end).title(""));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start,14));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Change SupportMapFragment to MapFragment. Something like this
MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map);
Please remove the ;; that you have used and put a single ;
And instead of:
int startLat = Integer.parseInt(ar1[0]);
int startLong = Integer.parseInt(ar1[1]);;
int endLat = Integer.parseInt(ar1[2]);;
int endLong = Integer.parseInt(ar1[3]);;
Please put:
double startLat = Double.parseDouble(ar1[0]);
double startLong = Double.parseDouble(ar1[1]);
double endLat = Double.parseDouble(ar1[2]);
double endLong = Double.parseDouble(ar1[3]);
We are using double because the constructor of LatLng takes two double arguements.
And please note that because of your first statement Log.e("Reader Stuff",reader.readLine()); the first line of the text file will not be parsed because a line is being read and logged and the next time you call reader.readLine(), you will get the second line.
Edit:
Maybe you are not able to see the markers because you haven't moved the map camera. To move the camera to any marker:
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start,14));
start is the LatLng and 14 is the Zoom level.

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)

Categories