How to get current location when app launch? - android

In this case the map appears on the application that I'm trying to make, but when the application is opened folder appears not in the current location but in Sout Atlantic Ocean. Is there a way to bring up the current location at the time the application is opened?
Here is my code :
public class GmapFragment extends Fragment implements OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback,
LocationListener
{
GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
double longitude;
double latitude;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gmaps, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LocationManager locManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if(network_enabled){
location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
longitude = location.getLongitude();
latitude = location.getLatitude();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(-7.0559935,110.4320226))
.title("Kos Munyiq"));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(-7.0500666,110.4264657))
.title("Kos Pos"));
mMap.animateCamera(CameraUpdateFactory.zoomTo(0));
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(false);
}
}
}
#Override
public void onLocationChanged(Location location) {
}
}
Sorry if there is something wrong with my question.

You are adding marker in someplace. Try use the following code instead of those markers..
mMap.setMyLocationEnabled(true); <<this is the main line
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
The on location change functionality will give you your position even if you change your location... If you just need your current position, static, you will just need the following code,
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("It's Me!"));
Then you will want to animate the camera, zoom in/zoom out a little bit.
Hope it helps. Cheers!

Related

Google map i am getting current location when i am change location marker does not moves in google map

Here is my code:
public class MapViewFragment extends Fragment implements OnMapReadyCallback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.maps, container, false);
Context context =this.getContext();
GPSService mGPSService = new GPSService(context);
mGPSService.getLocation();
if (mGPSService.isLocationAvailable == false) {
} else {
// Getting location co-ordinates
lat1 = mGPSService.getLatitude();
lng1 = mGPSService.getLongitude();
}
mMapView.onCreate(savedInstanceState);
ActivityCompat.requestPermissions(getActivity(),new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
call.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
call();
}
});
mMapView.getMapAsync(this); //this is important
}
});*/
}
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
m1 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1,lng1))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.anchor(0.5f, 0.5f)
.title("Title1")
.snippet("Snippet1"));
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
In program i getting current location lat and lang.When i moved to other location marker does not change. whenever I move the location has to change.
Current location value iam getting whenever i move location value does not change.want implement any method change the location.
i assume you've already created a marker to indicate your current position. like this
Marker currentLocation;
Now You need to implement LocationListener and update your MapView in the onLocationChanged callback
#Override
public void onLocationChanged(Location location) {
if(currentLocation != null){
currentLocation.remove();
}
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
currentLocation = googleMap.addMarker(new MarkerOptions().position(latLng)));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}

I can't get the location from locationlistener

I used a Fragment implements LocationListener and i tried to get my current location , but i can't get it successfully. Do i miss something ?
public class TrafficInformation extends Fragment implements LocationListener{
private MapView mapView;
private GoogleMap googleMap;
private double myLatitude,myLongitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
//part of android 6.0 permission
int flag = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (flag != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
googleMap.setMyLocationEnabled(true);
}
// For dropping a marker at a point on the Map
//i set my current location over here-------------------
LatLng sydney = new LatLng(myLatitude, myLongitude);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
//For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
i try to get it from this function:
#Override
public void onLocationChanged(Location location) {
myLatitude=location.getLatitude();
myLongitude=location.getLongitude();
}
i can't get myLatitude and myLongitude location , why?
any help would be grateful.
You are not calling
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this)
You are only calling
googleMap.setMyLocationEnabled(true);
This don't request for location updates... just set a pin on your position on the map.
Check here to see how to request current location:
https://developer.android.com/training/location/receive-location-updates.html

I want to replace a Marker from a map when user visits that location ( gets near a Marker )

First, I plot a Marker like this:
public void addMarker(String title,String lat,String Lng,int id,String address,int f)
{
marker= mMap.addMarker(new MarkerOptions().snippet(title)
.title(title+", "+address)
.position(new LatLng(Double.valueOf(lat), Double.valueOf(Lng)))
.icon(BitmapDescriptorFactory.fromResource(id)));
LatLng coordinate = new LatLng(Double.valueOf(lat), Double.valueOf(Lng));
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 10);
mMap.animateCamera(yourLocation);
mMarkerArray.add(marker);
}
After that I am trying to replace the Marker with another icon when ever I reached at any existing Location
#Override
public void onLocationChanged(Location location)
{
Log.d("latitude_main", "onlocation???");
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.e("latitude_main", "latitude--" + latitude+"longitude="+longitude);
current_lat= String.valueOf(latitude);
current_lng= String.valueOf(longitude);
Log.e("latitude_main","size-=="+salesmanlocationArrayList.size() );
for(int i=0;i<salesmanlocationArrayList.size();i++)
{
if(salesmanlocation.getLati().equals("12.9165757") && salesmanlocation.getLongi().equals("77.6101163"))
{
mMap.addMarker(new MarkerOptions()
.snippet(""+i).title(salesmanlocation.getFirm_name()+", "+salesmanlocation.getAddress())
.position(new LatLng(Double.valueOf(salesmanlocation.getLati().toString()), Double.valueOf(salesmanlocation.getLongi().toString())))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.event_events_select)));
}
mapFragment.getMapAsync(this);
}
}
I want to remove the marker from the map when the user visits that location.
You can simply define one OnMyLocationChangeListener class that performs your tasks, and set it on your GoogleMap instance, this way you can use it whenever you want in your application.
Step 1 - define your listener
public class MyMarkerLocationListener implements GoogleMap.OnMyLocationChangeListener {
List<Marker> markerList;
int MY_DISTANCE;
GoogleMap mMap;
public MyMarkerLocationListener(List<Marker> markerList, int meters, GoogleMap mMap)
{
this.markerList = markerList;
this.MY_DISTANCE = meters;
this.mMap = mMap;
}
#Override
public void onMyLocationChange(Location location) {
// your code/logic
//...
Location myNewLocation = location;
Location someMarkerLocation = new Location("some location");
//for each marker on your list
//check if you are close to it
for (Marker m : markerList) {
LatLng markerPosition = m.getPosition();
someMarkerLocation.setLatitude(markerPosition.latitude);
someMarkerLocation.setLongitude(markerPosition.longitude);
if (myNewLocation.distanceTo(someMarkerLocation) < MY_DISTANCE) {
//remove marker
m.remove();
//or if you still want to use it later
//m.setVisible(false);
// add your new marker
//mMap.addMarker(new MarkerOptions().icon()....);
}
}
}
}
After defining your class you just set the listener on your map on your fragment or activity code =)
Step 2 - instanciate the listener and set it
MyMarkerLocationListener myListener = new MyMarkerLocationListener(mMarkerArray, 100, mMap);
mMap.setOnMyLocationChangeListener(myListener);
UPDATE to answer your question in the comments:
You should initialize mMap before using it, take a look at this piece of code from this Stackoverflow question
public class MapPane extends Activity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
map.setTrafficEnabled(true);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
}
don't forget your activity should implement the OnMapReadyCallback interface so the onMapReady method is called
you can use the map only after it is ready
Hope this helps!

How to addMarker directly on GoogleMap after click button setMyLocationEnabled?

I made a code.
In this code, when i click a map, there will be a marker on clicked point.
This is my Code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "oh, no", Toast.LENGTH_LONG).show();
}
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
String lat = String.valueOf(point.latitude);
String lng = String.valueOf(point.longitude);
MarkerOptions marker = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title("ok");
mMap.addMarker(marker);
}
});
}
}
Question :
What i want is that when i click SetMylocationEnable button, there also added a new marker. And because i want marker is only one in whole map, another marker that has been in the map before is to be removed. How can i do it? Would you teach me?
You can see what button i saying is, in picture. (picture is from : Enable my location icon Googlemap v2)
mMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location location = getLocation();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())).title("ok");
mMap.addMarker(marker);
return true;
}
});
private Location getLocation() {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
return locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
}
keep a reference to the marker, if the reference is null then create the marker as you have done, if it is not, then edit the marker and change its location

control user gesture on my map

I new in coding google map,
my question is how i control the user gestur drag , zoom in and zoom out.
because my code always back to the current location of user when i zoomin/out, nad when i drag/ scroll up, down, left, right. always back to the current possition .
its my code for current loc user
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
}
};
You can use a boolean to move the camera only the first time:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
private Marker mMarker;
private boolean firstTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if (firstTime) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
firstTime = false;
}
}
}
NOTE: Take into account that this example uses GoogleMap.OnMyLocationChangeListener only because that is the method that you are using in your question, but it's deprecated and you must use the FusedLocationProviderApi according to the documentation:
public final void setOnMyLocationChangeListener
(GoogleMap.OnMyLocationChangeListener listener)
This method was deprecated. use
com.google.android.gms.location.FusedLocationProviderApi instead.
FusedLocationProviderApi provides improved location finding and power
usage and is used by the "My Location" blue dot. See the
MyLocationDemoActivity in the sample applications folder for example
example code, or the Location Developer Guide.

Categories

Resources