google map load map using internet or gps - google-maps

I want to use google map v2 to load the map using either gps or internet, I can do it using just internet.
when I connect my application to internet, the map is loaded successfully, but if i used just gps the map doesn't show even though I have already activiate the gps in my phone and in my app.
this is my code, first i get my location then i load the mapp
setContentView(R.layout.google_map_layout);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Toast.makeText(RestaurantsNearBy.this,
location.getLatitude() + "", Toast.LENGTH_LONG).show();
LatLng currentLocation = new LatLng(location.getLatitude(),
location.getLongitude());
new getRestaurantNearBy().execute(currentLocation.latitude,
currentLocation.longitude);
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setInfoWindowAdapter(new InfoWindowAdapter() {
private final View window = getLayoutInflater().inflate(
R.layout.restaurant_marker, null);
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
TextView tv_title = ((TextView) window
.findViewById(R.id.tv_title));
TextView tv_description = ((TextView) window
.findViewById(R.id.tv_description));
ImageView iv_image = ((ImageView) window
.findViewById(R.id.iv_image));
AddressMap oneAddres = markersMap.get(marker);
tv_title.setText(oneAddres.getRestaurant().getName());
tv_description.setText(oneAddres.getDescription());
Restaurant r = markersMap.get(marker).getRestaurant();
if (Restaurant.getRestaurant(r.getID()) != null) {
if (Restaurant.getRestaurant(r.getID()).getImage() != null) {
iv_image.setImageBitmap(Restaurant
.getRestaurant(r.getID()).getImage());
} else {
try {
iv_image.setImageBitmap(r
.getImageFromWebService());
} catch (Exception e) {
iv_image.setImageResource(R.drawable.unknown);
}
}
} else {
iv_image.setImageBitmap(r.getImageFromWebService());
}
return window;
}
});
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
final AddressMap oneAddress = markersMap.get(marker);
AlertDialog alertDialog3 = new AlertDialog.Builder(
RestaurantsNearBy.this).create();
alertDialog3.setTitle("Order !");
alertDialog3
.setMessage("Do you want to order from the restaurant "
+ oneAddress.getRestaurant().getName());
alertDialog3.setIcon(R.drawable.more_information);
alertDialog3.setButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Basket.setRestaurant(oneAddress
.getRestaurant());
dialog.dismiss();
Intent addAddressIntent = new Intent(
RestaurantsNearBy.this,
OrderMeal.class);
startActivity(addAddressIntent);
}
});
alertDialog3.setButton2("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog3.show();
}
});
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
currentLocation, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
Log.d("Provider ", provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(RestaurantsNearBy.this, "Sorry we couldn't define your location",
Toast.LENGTH_SHORT).show();
}
}

You should use proper tags, Google Maps can be found on loads of platforms, and you have a question about the android versions, so at least add Android tag.
On the question: Google Maps NEEDS active internet connection, when you first load the maps. V2 does some decent caching on your SD card (sometimes a bit excessive too), allowing you to later check thoose already loaded maps offline, but the principle is: no active internet connection, no Google Maps.
ps: GPS is NOT an internet connection.

By default you can't load the map data properly if you aren't connected with wifi or mobile connection. GPS only lets you find your position.

Related

Xamarin Forms - custom map marker not visible

I am following article on MS page about Custom map renderer and I can not get it to work for android. Map shows but pins (Markers) are not there. I did not found what I did different from official documents (as in previous link). When I debug, there are 3 markers in customPins collection. And custom renderer works in UWP. So issue is only in Android code.
Here is my CustomRender code for Android which does not shows pins.
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using iVanApp;
using iVanApp.Android.CustomMapRenderers;
using iVanApp.Droid;
using iVanApp.Model;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
[assembly: ExportRenderer(typeof(NightMap), typeof(MapRenderers))]
namespace iVanApp.Android.CustomMapRenderers
{
public class MapRenderers : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<NightPin> customPins;
public MapRenderers(Context context) : base(context)
{
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (NightMap)e.NewElement;
customPins = formsMap.NightPins;
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Name))
{
}
}
NightPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
public global::Android.Views.View GetInfoContents(Marker marker)
{
var inflater = global::Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as global::Android.Views.LayoutInflater;
if (inflater != null)
{
global::Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
view = inflater.Inflate(Resource.Layout.mtrl_layout_snackbar_include, null);
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public global::Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
}
}
DOes anyone have idea why this would not work?
Note: I had to modify official MS code because I got errors. Wherever is Android.Views.View I had to modify it to global::Android.Views.View otherwise I got following error
"'MapRenderers' does not implement interface member
'GoogleMap.IInfoWindowAdapter.GetInfoContents(Marker)'.
'MapRenderers.GetInfoContents(Marker)' cannot implement
'GoogleMap.IInfoWindowAdapter.GetInfoContents(Marker)' because it does
not have the matching return type of 'View'.".
and
The type or namespace name 'Views' does not exist in the namespace
'iVanApp.Android' (are you missing an assembly reference?)
Hope this did not break my code.
After investigating and reading about custom map issues (and mostly solutions) from others I got a workaround solution how to get pins on map but does not show info window when I click on pin(marker). Here I found workaround. If I modify OnMapReday and call&add method SetMapMarkers then pins are visible but as I said no info window is shown when I click on pin
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
SetMapMarkers();
}
private void SetMapMarkers()
{
NativeMap.Clear();
foreach (var pin in customPins)
{
NativeMap.AddMarker(CreateMarker(pin));
}
}
Although this is solution, I would prefer if I could get it to work without this workaround. Hence I did not put much effort why info window is not shown when you click on pin. In case there would be no solution without this workaround then I will be interested in solution with workaround but as I said I do not prefer to go this way.
As FreakyAli said that adding a custom pin and positions for CustomMap.
<local:CustomMap x:Name="customMap" MapType="Street" />
Adding a custom pin and positions the map's view with the MoveToRegion method
public MainPage()
{
InitializeComponent();
var pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(37.79752, -122.40183),
Label = "Xamarin San Francisco Office",
Address = "394 Pacific Ave, San Francisco CA",
Id = "Xamarin",
Url = "http://xamarin.com/about/"
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
I can get InfoWindow by clicking map pin, having no problem.

Bad location Google Maps Xamarin Forms (Middle of the ocean)

I'm using Xamarin.forms.Maps and ExtendedMap, I did make a custom control, here I can get the location when the user tap on map but by default the map position is in the middle of the occean, something like this 0.0756931, 0.0786793. I was seaching and trying for a while but I did not find the solution.
I did see that the map is loading the region.LatitudeDegrees and region.LongitudeDegrees but I really don't why is this happen.
Xamarin.Forms 3.0.0.482510
Xamarin.Forms.Maps 3.0.0.482510
Xamarin.Plugin.ExternalMaps 4.0.1
MapGoogleView.xaml
<local:ExtendedMap
WidthRequest="320" HeightRequest="200"
x:Name="MyMap" Tap="OnTap"
IsShowingUser="true"
MapType="Street"/>
MapGoogleView.xaml.cs
public MapGoogleView(double lat, double lon)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
var map = new ExtendedMap(
MapSpan.FromCenterAndRadius(
new Position(lat, lon), Distance.FromMiles(0.3)))
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 900,
VerticalOptions = LayoutOptions.FillAndExpand,
MapType = MapType.Street
};
var stack = new StackLayout { Spacing = 0 };
stack.Children.Add(map);
Content = stack;
var position = new Position(lat, lon); // Latitude, Longitude
var pin = new Pin
{
Type = PinType.Generic,
Position = position,
Label = "UbicaciĆ³n",
Address = "Latitud: " + lat.ToString() + ", Longitud: " + lon.ToString(),
};
MyMap.Pins.Add(pin);
map.MoveToRegion(
MapSpan.FromCenterAndRadius(
new Position(lat, lon), Distance.FromMiles(1)));
}
ExtendedMap.cs
public class ExtendedMap : Map
{
public event EventHandler<TapEventArgs> Tap;
public ExtendedMap()
{
}
public ExtendedMap(MapSpan region) : base(region)
{
}
public void OnTap(Position coordinate)
{
OnTap(new TapEventArgs { Position = coordinate });
}
public async void OnTap(Position coordinate)
{
try
{
OnTap(new TapEventArgs { Position = coordinate });
}
catch (Exception error)
{
await Application.Current.MainPage.DisplayAlert(
"Error",
error.Message,
"Aceptar");
return;
}
}
protected virtual void OnTap(TapEventArgs e)
{
var handler = Tap;
if (handler != null) handler(this, e);
}
}
public class TapEventArgs : EventArgs
{
public Position Position { get; set; }
}
}
Droid
ExtendedMapRenderer.cs
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public void OnMapReady(GoogleMap googleMap)
{
_map = googleMap;
if (_map != null)
//_map.GestureRecognizer.Add(new);
_map.MapClick += googleMap_MapClick;
}
public ExtendedMapRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e) //cambiar a xamarin.forms.view
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
If you're struggling to obtain the Latitude and Longitude coordinates using the plugins described above, you could obtain your devices lon/lat by doing the following:
Download and install into your application the Geolocator Plugin. Made by the man the myth the legend James Montemagno.
Following that, you can follow this guide to obtain your devices longitude and latitude coordinates.
On doing that you can assign your global lat and lon variables to the values retrieved using that plugin. I don't know if you did this prior to instantiating your maps or have used a different method but this is how I get my devices Lat & Lon.
As a fallback if a device has location disabled or does not have the ability to retrieve its GPS data I always set my default lat & lon to the capital city of the devices country region.
RegionInfo.CurrentRegion
then if UK set the lat & lon to london city center for example.

Mark Mobile Location on Google Map using Xamarin.Android

Sir,
Developed an application using Xamarin on Visual Studio 2017 where I need to locate the current location of mobile when user turn on Location on his android device and then mark that location on Google Map using MarkerOption. For this I have followed steps as guided in following video https://www.youtube.com/watch?v=rCZN1c2azyE. But didn't got current location on map.
Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Gms.Maps;
using Android.Locations;
using Android.Util;
using Android.Gms.Maps.Model;
namespace smvdappdev
{
[Activity(Label = "LOCATION MAP")]
//for google map, for gps location
public class UserLocationMap_Act : Activity, IOnMapReadyCallback, ILocationListener
{
//Map variable
private GoogleMap gooMap;
//Location
LocationManager locManager;
String provider;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.UserLocationMap);
//Back Button
ActionBar.SetDisplayHomeAsUpEnabled(true);
//Method for Map
SetUpMap();
locManager = (LocationManager)GetSystemService(Context.LocationService);
provider = locManager.GetBestProvider(new Criteria(), false);
Location location = locManager.GetLastKnownLocation(provider);
if (location == null)
{
System.Diagnostics.Debug.WriteLine("No location available!");
}
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
Finish();
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
//for setting map on fragment placed on activity page
private void SetUpMap()
{
if (gooMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.fragment1).GetMapAsync(this);
}
}
//to draw map on map display view
public void OnMapReady(GoogleMap googleMap)
{
this.gooMap = googleMap;
//LatLng latlng = new LatLng()
//MarkerOptions mo = new MarkerOptions();
//mo.SetPosition(new LatLng(Convert.ToDouble(32.73), Convert.ToDouble(74.86)));
//mo.SetTitle("Civil Secretarait Jammu");
//googleMap.AddMarker(mo);
googleMap.UiSettings.CompassEnabled = true;
googleMap.UiSettings.ZoomControlsEnabled = true;
googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());
//throw new NotImplementedException();
}
//*** Here all code for getting location via GPS
protected override void OnResume()
{
base.OnResume();
provider = LocationManager.GpsProvider;
//if (locManager.IsProviderEnabled(provider))
//{
locManager.RequestLocationUpdates(provider, 2000, 1, this);
//}
//else
//{
// Log.Info(tag, provider + " is not available. Does the device have location services enabled?");
//}
}
protected override void OnPause()
{
base.OnPause();
locManager.RemoveUpdates(this);
}
public void OnProviderEnabled(string provider)
{
}
public void OnProviderDisabled(string provider)
{
}
public void OnStatusChanged(string provider, Availability status, Bundle extras)
{
}
public void OnLocationChanged(Location location)
{
Double lat, lng;
lat = location.Latitude;
lng = location.Longitude;
MarkerOptions mo = new MarkerOptions();
mo.SetPosition(new LatLng(lat, lng));
//Toast.MakeText(this, "Latitude:" + lat.ToString() + ", Longitude:" + lng.ToString(), ToastLength.Long).Show();
mo.SetTitle("You are here!");
gooMap.AddMarker(mo);
CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
builder.Target(new LatLng(lat, lng));
CameraPosition camPos = builder.Build();
CameraUpdate camUpdate = CameraUpdateFactory.NewCameraPosition(camPos);
gooMap.MoveCamera(camUpdate);
}
}
}
You can just use gooMap.MyLocationEnabled = true. You need to check and request location permission first in order for this to work.
With MyLocationEnabled set to true, it will show a precision circle and a blue dot showing where you are.

I am trying to show nearby places for fixed location

This is the link that i have refereed but when i enter the name like atm or school in search box it gives me error in
PlacesDisplayTask.java on googleMap.clear()
NullPointer exception
http://javapapers.com/android/find-places-nearby-in-google-maps-using-google-places-apiandroid-app/
I tried another code
this is
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighborhood);
// 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);
*/
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = (Button) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
fragment.getMapAsync(this);
// Enabling MyLocation in Google Map
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider,this );
// Setting click event lister for the find button
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=YOUR_API_KEY");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
// Clears all the existing markers
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
/**
* 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) {
googleMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(19.0330488, 73.0296625);
googleMap.addMarker(new MarkerOptions().position(sydney).title("CBD"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
googleMap.setMinZoomPreference(15.0f);
googleMap.setMaxZoomPreference(20.0f);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
googleMap.setMyLocationEnabled(true);
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Neighborhood Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.soulsystem_4.myapplication/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Neighborhood Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.soulsystem_4.myapplication/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
What shoul i pass 4th parameter in locationManager.requestLocationUpdates(provider, 20000, 0, );
it is always saying cast 4th parameter to location listener and when i cast it still it gives me error cannot be cast to android.location.LocationListener
Change Location listener to ClientAngent ist new in api. They I ahve changed it.
Refer https://developers.google.com/places/android-api/

Embedded Google Map can't get current location in WebView

I followed this tutorial: http://android-er.blogspot.com/2013/03/embed-google-map-in-webview.html
I'm trying to just use the Google Map in the WebView, but it can't get my current location. I've enabled JavaScript on the WebView. What else do I have to enable?
Does anyone know why that might be? Shouldn't it prompt me to use my current location?
Note that I am not interested in using a MapView as an alternative whatsoever. I'm trying to find out what I need to set on the WebView or maybe on the device's location services?
You should permit the web view to access your location by overriding the method onGeolocationPermissionsShowPrompt like this:
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
});
On API 5.x and below, you will need
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
in your AndroidManifest.xml.
But to allow permissions for geolocation on API 6.0+, you have to request the permission at runtime.
To do this, use
private String mGeolocationOrigin;
private GeolocationPermissions.Callback mGeolocationCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// other setup
myWebView.setWebChromeClient(new MyWebChromeClient());
}
private WebChromeClient mWebChromeClient = new WebChromeClient() {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Geolocation permissions coming from this app's Manifest will only be valid for devices with API_VERSION < 23.
// On API 23 and above, we must check for permission, and possibly ask for it.
final String permission = Manifest.permission.ACCESS_FINE_LOCATION;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_GRANTED) {
// we're on SDK < 23 OR user has already granted permission
callback.invoke(origin, true, false);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
// user has denied this permission before and selected [/] DON'T ASK ME AGAIN
// TODO Best Practice: show an AlertDialog explaining why the user could allow this permission, then ask again
} else {
// ask the user for permissions
ActivityCompat.requestPermissions(MainActivity.this, new String[] {permission}, RP_ACCESS_LOCATION);
mGeolocationOrigin = origin;
mGeolocationCallback = callback;
}
}
}
}
and receive the result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case RP_ACCESS_LOCATION:
boolean allow = false;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user has allowed these permissions
allow = true;
}
if (mGeolocationCallback != null) {
mGeolocationCallback.invoke(mGeolocationOrigin, allow, false);
}
break;
}
}
in your activity.
You can try GreenDroid with Google Maps.
Checkt it out: https://github.com/cyrilmottier/GreenDroid
You'd have to enable android.permission.ACCESS_FINE_LOCATION and android.permission.INTERNET,
Create a LocationManager instance and LocationListener instance
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
and add onLocationChanged(Location loc) method that inside of it have your loc generate the longitude and latitude (String long = loc.getLongitude(); String lat = loc.getLatitude();)
and now use long, lat to generate your mapPath string and continue to generate the WebView
You can use this for ref: http://www.rdcworld-android.blogspot.in/2012/01/get-current-location-coordinates-city.html