How Can draw a path between two latitude longitude in google map? - android

There are latitude and longitude of two place is given.This is my map activity:
#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;
// double array [] = {44.968046 ,-94.420307 ,44.33328,-89.132008, 33.755787,-116.359998,33.844843,-116.54911 ,44.92057 ,-93.44786};
// Add a marker in Sydney and move the camera
double lat1 = 23.781388 ;
double lon1 = 90.425500 ;
double lat2 = 23.780270 ;
double lon2 = 23.780270 ;
LatLng place1 = new LatLng( lat1, lon1);
LatLng place2 = new LatLng( lat2, lon2);
mMap.addMarker(new MarkerOptions().position(place1).title("Marker in Pran RFL"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place1));
mMap.addMarker(new MarkerOptions().position(place2).title("Marker in Gulshan"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place2));
}
I want to draw a path between this couple of latitude and longitude.How Can I do it?

You have to add PolyLineOptions and add new LatLng() try this code
PolylineOptions options = new PolylineOptions();
options.color( Color.parseColor( "#CC0000FF" ) );
options.width( 5 );
options.visible( true );
options.add( new LatLng( lat1 ,lon1) );
options.add( new LatLng( lat2 ,lon2) );
mMap.addPolyline( options );

Related

Google map is not updating LatLong with location change

to start with, I am completely confused with various api's available for location and map. So, I even dont know if the code is optimal for sdk 27.(I have minimum sdk 24 set.)
The problem is this piece of code shows the current location well and fine, butand the map gets updated when the location is changed. But, that is not reflected in location. See, the polyline drawn from LatLong does not follow the current location.
Also, I am trying to implement FusedLocationProviderClient but thats probably not the case here.
Any help will be very welcome.
public class SecondFragment extends Fragment implements OnMapReadyCallback {
//Color stroke = new Color(222.0,135.0, 135.0,174.0);
private GoogleMap mMap;
public static SecondFragment newInstance() {
SecondFragment fragment = new SecondFragment();
return fragment;
}
public GoogleMap getMap() {
return mMap;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double latitude;
double longitude;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
latitude = 0.0;
longitude = 0.0;
} else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
latlang.Lat = latitude;
latlang.Lang = longitude;
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(18).build();
double angle = Math.toRadians(93.833);
Point cPoint = mMap.getProjection().toScreenLocation(new LatLng(latitude,longitude));
System.out.println("mPoint X"+ cPoint.x);
System.out.println("mPoint Y"+ cPoint.y);
Point mPoint = new Point();
//Azimuth Pos only
double lat_azi = 2*Math.sin(angle)+cPoint.y;
double long_azi = 2*Math.cos(angle)+cPoint.x;
LatLng nat_azi =mMap.getProjection().fromScreenLocation(mPoint);
//private List<Point> mPoint = new ArrayList<Point>();
Marker marker = mMap.addMarker(new MarkerOptions()
.position(nat_azi)
.anchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sun_pos_icon))
);
Marker marker_loc = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
mMap.addPolyline(new PolylineOptions()
.add(new LatLng(lat_azi, long_azi), new LatLng(latitude, longitude), new LatLng(0,0))
.width(15)
.color(Color.MAGENTA));
PathOfSun.getTime();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
}
You can follow below link for Updating Marker position on the Map.
Move marker with gps in google map android

Cluster with markers in desired locations

I'm new to programming in Android, I'm developing an application which shows some markers that I'm giving you by code, when adding a cluster, it marks me a few default points.
I would like to know how do I change those default points in the cluster and add the markers to the points I want?
private void addItems() {
double lat = 3.424014;
double lng = -76.536218;
for (int i = 0; i < 5; i++) {
double offset = i / 60d;
lat = lat + offset;
lng = lng + offset;
MyItem offsetItem = new MyItem(lat, lng);
mClusterManager.addItem(offsetItem);
}
}
#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);
btnclute=(Button)findViewById(R.id.btn_cluster);
//cluster
btnclute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(3.422504, -76.538128), 13));
mClusterManager = new ClusterManager<MyItem>(getBaseContext(), mMap);
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
addItems();
}
});
}
/**
* 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;
mapa= googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
//Marker
//Estadio
LatLng home = new LatLng(3.429862, -76.541336);
dato=getResources().getString(R.string.estadio);
mMap.addMarker(new MarkerOptions().position(home).title(dato)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.estadio)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home, 13));
//Sebastian Belalcazar
LatLng home1 = new LatLng(3.449151, -76.545185);
dato1=getResources().getString(R.string.sebas);
mMap.addMarker(new MarkerOptions().position(home1).title(dato1)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sebastian)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home1, 13));
//Cristo Rey
LatLng home2 = new LatLng(3.435855, -76.564840);
dato2=getResources().getString(R.string.rey);
mMap.addMarker(new MarkerOptions().position(home2).title(dato2)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.cristo)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home2, 13));
//Tres cruces
LatLng home3 = new LatLng(3.467800, -76.545473);
mMap.addMarker(new MarkerOptions().position(home3).title(getResources().getString(R.string.cruces))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.tres)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home3, 13));
//Plaza de Caicedo
LatLng home5 = new LatLng( 3.451864, -76.532479);
dato3=getResources().getString(R.string.plaza);
dato4="-" + getResources().getString(R.string.caicedo);
dato5="-" + getResources().getString(R.string.pedro);
dato6="-" + getResources().getString(R.string.palacio);
mMap.addMarker(new MarkerOptions().position(home5).title(dato3)
.snippet(dato4 + "\n" +
dato5 + "\n" +
dato6)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.plaza)));
mapa.moveCamera(CameraUpdateFactory.newLatLngZoom(home5, 13));
You need to set an algorithm so the clusters don't align in a grid, thus becoming more precise.
NonHierarchicalDistanceBasedAlgorithm<ClusterItem> algo = new NonHierarchicalDistanceBasedAlgorithm<>();
mClusterManager.setAlgorithm(algo);
//If that isn't enough you can change the latlng
Collection<ClusterItem> col = algo.getItems();
for (ClusterItem clusterItem : col) {
clusterItem.getPosition().latitude = yourNewLatitude;
clusterItem.getPosition().longitude = yourNewLongitude;
}

Two MapViews in one Android Activity: jumping/flickering Markers

I'm developing an Android App for Tablets, which shows two maps with markers in master-detail-layout.
Both maps contain different markers. When I start to move the camera in one of the maps, markers on the other map start to jump/flicker and sometimes even stay in wrong locations.
I was able to reproduce the problem with the google-maps android-samples
by simply adding some markers to two of the maps, nothing more. The flickering is actually far worse than visible in the gif.
gif displaying jumping markers
Here's the whole changed Activity for completeness:
public class MultiMapDemoActivity extends AppCompatActivity {
private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multimap_demo);
final SupportMapFragment firstMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1);
firstMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
addMarkers(googleMap, multiplyMarkerPosition(BRISBANE));
addMarkers(googleMap, multiplyMarkerPosition(MELBOURNE));
addMarkers(googleMap, multiplyMarkerPosition(SYDNEY));
addMarkers(googleMap, multiplyMarkerPosition(ADELAIDE));
addMarkers(googleMap, multiplyMarkerPosition(PERTH));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ADELAIDE, 4f));
}
});
final SupportMapFragment secondMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2);
secondMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
addMarkersBlue(googleMap, multiplyMarkerPosition(new LatLng(51.51, 0)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.51, 0), 4f));
}
});
}
public List<LatLng> multiplyMarkerPosition(LatLng position) {
final LinkedList<LatLng> positions = new LinkedList<>();
final double latitude = position.latitude;
final double longitude = position.longitude;
final double delta = 1;
positions.add(new LatLng(latitude, longitude + delta));
positions.add(new LatLng(latitude, longitude - delta));
positions.add(new LatLng(latitude, longitude));
positions.add(new LatLng(latitude - delta, longitude + delta));
positions.add(new LatLng(latitude - delta, longitude - delta));
positions.add(new LatLng(latitude - delta, longitude));
positions.add(new LatLng(latitude + delta, longitude + delta));
positions.add(new LatLng(latitude + delta, longitude - delta));
positions.add(new LatLng(latitude + delta, longitude));
return positions;
}
public void addMarkers(GoogleMap map, List<LatLng> positions) {
for (LatLng latLng : positions) {
map.addMarker(new MarkerOptions().position(latLng));
}
}
public void addMarkersBlue(GoogleMap map, List<LatLng> positions) {
for (LatLng latLng : positions) {
map.addMarker(
new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
}
I couldn't find out whether this is a known bug or an unsupported mode of operation. If you have any ideas or possible workarounds, please let me know. Thanks.

Trying to get User location on a map in android

My code is totally fine, i want to get user location on the map as soon as the app is opened. But the app just crashes. Also the program is set to update location and add a marker as soon as its changed, nut that's also is not working. Here's the code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
#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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location= locationManager.getLastKnownLocation(provider);
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
// Add a marker and move the camera
}
#Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
Log.i("Latitude", lat.toString());
}
try This.
getLastKnownLocation returns if location is there in cache otherwise it returns null
add a check there
if(location!=null)
{
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title("Marker"));
}
2 solution use google play services fusedlocation api for better management with location refer here http://coderzpassion.com/android-location-using-google-play-services/
3 try this to addMarker
public void drawMarker(double lat,double lon)
{
if (mMap != null) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// Moving Camera to a Location with animation
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.addMarker(marker);
}
}
for more details refer here http://coderzpassion.com/android-google-maps-v2-tutorial-with-markers/

android locationListener not working?

I am having trouble using the loactionListener in eclipse for android. I have been googling for a while now an I can't seem to see why this shouldn't work. The only thing I can think of is that maybe it is because my testing device has no sim. (the internet is provided via wifi).
I have used this as a reference and still, nothing.
Could anyone help me with this problem.
here is the relevant parts of my activity:
public class MainMenu extends Activity implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
reverseGeoCode(lat, lng);
}
}
I was using a different method to display my location on the map, which worked well but it never updated. It always showed my location at the last place I used the GPS, which turns out was 60mile accross the country. I can see this is working but is there a better way of doing this.
Old method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
if(findViewById(R.id.the_map) != null){
//map has loaded continue
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng ;
if(lastLoc == null){
/* Use the LocationManager class to obtain GPS locations */
double latitude = 0;
double longitude = 0;
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.your_loc_icon))
.snippet(snippit));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lastLatLng) // Sets the center of the map to user position
.zoom(0) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(20) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
currentLoc = lastLatLng;
theMap.animateCamera (CameraUpdateFactory.newCameraPosition(cameraPosition), 3000, null);
final TextView geoTagText = (TextView)findViewById(R.id.text_geoTag);
geoTagText.setText("We cannot find your current location, please check your settings.");
}else{
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
}
}else{
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng;
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
//no map to load
}
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
}
it would also be useful to add that there is button to relocate the user manually if they want.
reLocBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(menuActive == true){
playSound();
LocationManager loc = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location gpsLoc = (Location) loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = gpsLoc.getLatitude();
double lng = gpsLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
animateMap(lastLatLng);
}
}
});
I'm not to sure why either method doesn't update, but the second method seams to work better on first load.
You don't appear to be using requestLocationUpdates() anywhere. In that method you pass a LocationListener object that it then calls for location updates.
i.e. in your case:
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If you are using Google Maps API v2, you can do it using that, for example:
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));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.

Categories

Resources