I have an an activity where the main view is Google maps. And I set up a marker when the map is initially loaded, but when I click on it I am not able to get the locality or anything. The maps appears, but I can't click on the marker, or tap or tap on the screen and hold to create a new marker. basically it cannot do anything...And i can't figure out why! Hope you guys can see something that I am not seeing.
Here is my main activity.
public class MapsActivity extends FragmentActivity {
//Maps
private GoogleMap mMap;
//Marker
private Marker marker;
//Location
private LocationListener locationListener = null;
private LocationManager locationManager = null;
private static final float DEFAULTZOOM = 15;
private double longitude_mapsActivity;
private double latitude_from_mapsActivity;
private String cityName_mapsActivity;
private String countryName_mapsActivity;
//ProgressBar
private ProgressBar myPB_MAPS;
//Buttons
private ImageButton fab_doneButton;
//SearchEditText
private EditText editText_Search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
});
//Get user current location.
//myPB_MAPS = (ProgressBar) findViewById(R.id.myPB_MAPS);
//initialize your map
initMap();
//FAB button
fab_doneButton = (ImageButton) findViewById(R.id.activity_maps_FAB_done);
fab_doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (countryName_mapsActivity == null) {
Toast.makeText(MapsActivity.this, "Location is null", Toast.LENGTH_SHORT).show();
} else {
Global_Class.getInstance().getValue().countryName_GLOBAL = countryName_mapsActivity;
Global_Class.getInstance().getValue().cityName_GLOBAL = cityName_mapsActivity;
Global_Class.getInstance().getValue().longitude_user_GLOBAL = longitude_mapsActivity;
Global_Class.getInstance().getValue().latitude_user_GLOBAL = latitude_from_mapsActivity;
//Go to make sure we're sending all the GPS info, so we set geoLocationFromMapsIsPresent to true.
FinishCard.geoLocationFromMapsIsPresent();
FinishCard.setComingBackFromMaps();
Intent FinishCardIntent = new Intent(MapsActivity.this, FinishCard.class);
startActivity(FinishCardIntent);
}
}
});
//EditText
editText_Search = (EditText) findViewById(R.id.maps_EditText);
editText_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
private void performSearch()
{
String location = editText_Search.getText().toString();
if(location.length() == 0)
{
Toast.makeText(this,"Please enter a location",Toast.LENGTH_SHORT).show();
return;
}
//1-first step
Geocoder gc = new Geocoder(this);
List<Address> list = null;//For this function I only want a single address.
try
{
//3-Third step
list = gc.getFromLocationName(location,10);
}
catch (IOException e)
{
e.printStackTrace();
}
//4-Fourth step
Address add = list.get(0);//Give me the first and only item of the list.
//5-fifth step
String locality = add.getLocality();//So if you enter Taj mahal you get Agra, the place where its at, thats what Address locality does.
double lat = add.getLatitude();
double lng = add.getLongitude();
//GoToLocation() method
gotoLocation(lat, lng, DEFAULTZOOM);
//For Removing existing markers.
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.draggable(true);
marker = mMap.addMarker(options);
}
private void gotoLocation(double lat, double lng, float zoom)
{
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
private void setMarker(String locality, String country, double lat, double lng)
{
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.draggable(true);
if(country.length() > 0)
{
options.snippet(country);//Background highlight TEXT SUPER IMPORTANT
}
//.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
marker = mMap.addMarker(options);//So here we connect our marker to our map, which is used in initMap.
}
private void initMap()
{
if(mMap == null)
{
if(mMap != null)
{
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener()
{
#Override
public void onMapLongClick(LatLng ll) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
MapsActivity.this.setMarker(add.getLocality(), add.getCountryName(), ll.latitude, ll.longitude);//this is where we set the orange marker.
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity= ll.longitude;
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker)
{
LatLng ll = marker.getPosition();
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity = ll.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
//Global_Class.getInstance().getValue().cardLocality = "Paris";
List<Address> list = null;
try
{
list = gc.getFromLocation(ll.latitude, ll.longitude,1);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
Address add = list.get(0);
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
return false;
}
catch (IndexOutOfBoundsException e)
{
return false;
}
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() //If you want to drag the original google maps marker you use this method, if you comment this out it will use the orange one.
{
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
LatLng ll = marker.getPosition();
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
marker.setTitle(add.getLocality());
marker.setSnippet(add.getCountryName());
//marker.showInfoWindow();
}
});
}
}
}
}
Here is my xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.daprlabs.swipedeck.GeoLocation.MapsActivity">
<RelativeLayout
android:layout_width="340dp"
android:layout_height="50dp"
android:background="#FFFFFF"
android:elevation="10sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/maps_EditText"
android:imeOptions="actionSearch"
android:inputType="text"/>
</RelativeLayout>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/myPB_MAPS"
android:layout_marginLeft="150dp"
android:layout_marginTop="55dp"/>
<ImageButton
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/circle_fab"
android:id="#+id/activity_maps_FAB_done"
android:layout_gravity="right|bottom"
android:src="#drawable/white_plus" />
</fragment>
You are contradicting yourself in your initMap().
Remove the following if statement:
if (mMap == null)
Also only call initMap() after mapFragment.getMapAsync returns. At this point, you know your map is ready to go.
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
initMap();
}
});
You are supposed to implement
OnMapReadyCallback
And in turn override
onMapReady
Now you can manipulate the Map within onMapReady. Before that, it is not certain that your Map has actually set properly.
Anything that manipulates the Map like loading markers over it and setting marker click listeners has to happen in onMapReady.
As an example of Map's manipulation at appropriate time, you can take hint from the following code where Map's camera is only set when it has properly set.
public class YourMapFragment extends Fragment implements OnMapReadyCallback {
...
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + lat + "Lng:" + log));
}
...
}
Related
I'm making a search bar with google maps.
If I try to search somewhere the app will shutdown
And this is the error I get
Caused by: 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
at com.example.yoons.honey.RealMap.onMapSearch(RealMap.java:71)
map.java
public class RealMap extends AppCompatActivity implements OnMapReadyCallback {
private Button searchButton;
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.real_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
searchButton = new Button(this);
searchButton.setOnClickListener(search);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private View.OnClickListener search=new View.OnClickListener(){
public void onClick(View v){
onMapSearch(v);
}
};
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() != 0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
} else {
Toast.makeText(getApplicationContext(), "location not found", Toast.LENGTH_SHORT).show();
}
}
}
}
I don't know why my code won't work
I copied most of the code on the internet
It's the most common search bar code I think but it doesn't work for me
Pass the googleMap reference to you variable mMap as:-
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
I have a google maps activity with a map an edittext and a button.
The screenshot of the activity that I have ready at the moment.
Whenever this activity is opened a marker is added to the map.
What I want further in this is that whenever the user inputs an address in that edittext and clicks the button, then another marker is added on the same map without erasing the previous marker and a polyline is created in the map joining the two markers.
I have tried adding the second marker but the app just crashes and I am not able to do that. It would be a great help if you guys can help me in adding the second marker.
Here is the activity code :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#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) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
EDIT 1
I finally got the answer myself, on where to add, it was basically a minor error but just so other people know where to add I will update the answer here :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#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);
findRouteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchString = findRouteEdittext.getText().toString().toLowerCase().trim();
if (searchString.equals("")){
// findRouteEditTextInputLayout.setErrorEnabled(true);
// findRouteEditTextInputLayout.setError("Enter a location or City!");
//use snackbar to show something.
}
else{
coder2 = new Geocoder(MapsActivity.this);
coord2 = null;
try {
addressList2 = coder2.getFromLocationName(searchString, 5);
if (addressList2 != null) {
Address location = addressList2.get(0);
coord2 = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (coord2!=null && coord!=null) {
mMap.clear();
mMarkerOptions2 = new MarkerOptions();
mMarkerOptions2.position(coord2);
mMarkerOptions2.title(searchString); //this is the address of the new string entered by the user
mMap.addMarker(mMarkerOptions2).showInfoWindow();
mMarkerOptions3 = new MarkerOptions();
mMarkerOptions3.position(coord);
mMarkerOptions3.title(completeAddress); //this is the address of the original string received from intent
mMap.addMarker(mMarkerOptions3).showInfoWindow();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
If you already got Location object then use below code to add new marker in to map.
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
place this code in side add button on click listener.
I have been googling this for hours but no luck so far.
I want to get the address of the location where the map is touched / tapped.
I understand that in order to get the address i need to reverse geocode the coordinates. But how do i get the coordinates from the map in the first place?
All you need to do is set up a OnMapClickListener, and then the onMapClick() override will give you a LatLng object. Then, use a Geocoder object to get the address of the point that was just clicked on.
In this simple example, I've also added a Marker every time the user clicks a new point on the map.
Here is the main piece of functionality that you need:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
//save current location
latLng = point;
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(point.latitude, point.longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
android.location.Address address = addresses.get(0);
if (address != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
sb.append(address.getAddressLine(i) + "\n");
}
Toast.makeText(MapsActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
Here is the full class that I used to test this:
public class MapsActivity extends AppCompatActivity {
private GoogleMap mMap;
private LatLng latLng;
private Marker marker;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
geocoder = new Geocoder(this, Locale.getDefault());
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
//save current location
latLng = point;
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(point.latitude, point.longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
android.location.Address address = addresses.get(0);
if (address != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
sb.append(address.getAddressLine(i) + "\n");
}
Toast.makeText(MapsActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
}
}
Result of tapping the map in two different points:
Google Map has callbacks to do that like this one or this one.
Just implement them in your code and as soon as they're fired, just make a reverse geocode the coordinates. You actually found the most complicated part (you understood that you need to reverse geocode).
I have implemented Google maps v2 for Android app. My location, marker everything is showing fine, but when I am on move OnMylocationChange is called and marker is updated, but I have to scroll up or down as the view of my location goes off the map.
How do I update my map to scroll with my current location? Like Google Maps App.
#Override
public void onMyLocationChange(Location location)
{
if (markermylocation != null)
{
markermylocation.remove();
}
curlat = location.getLatitude();
curlong = location.getLongitude();
myLocation(curlat, curlong, username, imageURL, ZOOMVALUE);
}
private void myLocation(double lat, double lng, String name, String url, float zoom)
{
if(firsttime == 1)
{
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
googleMap.animateCamera(update);
firsttime = 0;
}
final String uname = name;
curlat = lat;
curlong = lng;
Picasso.with(getActivity()).load(url).resize(120, 120).transform(transformation).into(new Target()
{
#Override
public void onBitmapFailed(Drawable arg0)
{
markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.profilepic)).title(uname).anchor(0.5f, 1f);
markermylocation = googleMap.addMarker(markerOptionsmylocaiton);
}
#Override
public void onBitmapLoaded(Bitmap b, LoadedFrom arg1)
{
bitmapMarkermylocation = BitmapDescriptorFactory.fromBitmap(b);
if(b != null)
{
markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(bitmapMarkermylocation).title(uname).anchor(0.5f, 1f);
}
else
{
markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.profilepic)).title(uname).anchor(0.5f, 1f);
}
markermylocation = googleMap.addMarker(markerOptionsmylocaiton);
}
#Override
public void onPrepareLoad(Drawable arg0)
{
}
});
}
Thanks!
I think you just have to remove the if (firsttime == 1) conditional, then the map should recenter whenever your location is updated.
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = null;
if(firsttime == 1) {
update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
firsttime = 0;
} else {
update = CameraUpdateFactory.newLatLng(ll);
}
googleMap.animateCamera(update);
is there a reason you have that in there?
as mentioned in spec:
CameraUpdateFactory is a class containing methods for creating CameraUpdate objects that change a map's camera. To modify the map's camera, call animateCamera(CameraUpdate), animateCamera(CameraUpdate, GoogleMap.CancelableCallback) or moveCamera(CameraUpdate), using a CameraUpdate object created with this class.
read more
so when you are implementing this :
markermylocation = googleMap.addMarker(markerOptionsmylocaiton);
take care of camera move with this methods:
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
I have a map with a lot of markers. When you click marker, small windows with information will appear. When you click it I want to call fragment. I found that I should use onInfoWindowClick but something is wrong. I can't get any values.
public class Map extends Activity implements OnInfoWindowClickListener{
static final LatLng xxx = new LatLng(70.000, 70,22);
static String[] streets;
static String[] artist;
Coordinate cor = new Coordinate();
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
Resources res = this.getResources();
artist = res.getStringArray(R.array.authors_nicks);
streets = res.getStringArray(R.array.streets);
for (int i = 0; i < cor.coordinatesVale.size(); i++) {
Marker m = googleMap.addMarker(new MarkerOptions()
.position(cor.coordinatesVale.get(i))
.title(artist[i])
.snippet(streets[i])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker)));
m.getId();
}
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xxx, 12));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onInfoWindowClick(Marker marker) {
String id = marker.getId();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("dsdsd", 3);
startActivity(i);
Log.i("dddd", id); /// CAN't see
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I found some tutorials, but I'm don't know what I'm doing wrong
In your initializeMap() function, right after you use getMap(), put the following code there. Using this method, you don't need to call implements OnInfoWindowClickListener, but would work the same either way.
if (googleMap != null) {
// More info: https://developers.google.com/maps/documentation/android/infowindows
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Determine what marker is clicked by using the argument passed in
// for example, marker.getTitle() or marker.getSnippet().
// Code here for navigating to fragment activity.
}
});
}
The above code allows you to do something when the user clicks on the info window.
In order to show the info window in the first place, use one either one of the following code snippets, which you have already:
static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400"));
Or,
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne"));
melbourne.showInfoWindow();
Source: Google Maps Android API v2