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

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.

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.

How to get Address from Lat Long

Hello i am creating App for iOS and Android. The issue i want to fix that on the load on page i want to display the map with the address. I can get Lat Long successfully but i cannot getting address that i want to display on a label. Below is my code that i am using.
using Plugin.Geolocator;
using Xamarin.Forms.Maps;
private Position _position;
// Map map;
double Lat, Long;
string address = "";
public TestPage()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
GetPosition();
if (_position != null)
{
Lat = _position.Latitude;
Long = _position.Longitude;
}
//Task<String> str = GetAddress();
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(Lat, Long), Distance.FromMiles(1)));
var position = new Position(Lat, Long);
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = ""
};
map.Pins.Add(pin);
var zoomLevel = 17.83;
var latlongdegrees = 360 / (Math.Pow(2, zoomLevel));
map.MoveToRegion(new MapSpan(position, latlongdegrees, latlongdegrees));
LabelTime.Text = DateTime.Now.ToString("hh:mm tt") + " " + DateTime.Now.ToString("MM/dd/yyyy");
string recentAddress = address; // trying to get adderss for location
}
GetPosition()
public async void GetPosition()
{
Plugin.Geolocator.Abstractions.Position position = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100.0;
position = await locator.GetLastKnownLocationAsync();
if (position != null)
{
_position = new Position(position.Latitude, position.Longitude);
//got a cahched position, so let's use it.
return;
}
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//not available or enabled
return;
}
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10), null, true);
}
catch (Exception ex)
{
// error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
}
_position = new Position(position.Latitude, position.Longitude);
if (position == null)
return;
}
GetAddress()
public async Task<String> GetAddress()
{
// string Addrsss = "";
try
{
Geocoder geoCoder = new Geocoder();
if (_position != null)
{
var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(_position);
await Task.Delay(2000);
foreach (var a in possibleAddresses)
{
address += a + "\n";
}
}
return address;
}
catch (Exception ex)
{
throw;
}
}
I also try to get the current address on OnAppearing()
protected override void OnAppearing()
{
this.Appearing += TestPage_Appearing; //Subscribe to event
base.OnAppearing();
}
protected async void TestPage_Appearing(object sender, EventArgs args)
{
GetPosition();
address= await GetAddress();
string a = address;
this.Appearing -= TestPage_Appearing; //Unsubscribe
}
You can get placemark address using Xamarin.Essentials as below,
protected async override void OnAppearing()
{
await GetAddress();
}
private async Task GetAddress()
{
var lat = 47.673988;
var lon = -122.121513;
var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);
var placemark = placemarks?.FirstOrDefault();
if (placemark != null)
{
var geocodeAddress =
$"AdminArea: {placemark.AdminArea}\n" +
$"CountryCode: {placemark.CountryCode}\n" +
$"CountryName: {placemark.CountryName}\n" +
$"FeatureName: {placemark.FeatureName}\n" +
$"Locality: {placemark.Locality}\n" +
$"PostalCode: {placemark.PostalCode}\n" +
$"SubAdminArea: {placemark.SubAdminArea}\n" +
$"SubLocality: {placemark.SubLocality}\n" +
$"SubThoroughfare: {placemark.SubThoroughfare}\n" +
$"Thoroughfare: {placemark.Thoroughfare}\n";
Console.WriteLine(geocodeAddress);
}
}
refer this link for in depth details
Also this one for detailed implementation

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.

how to add google map in windows phone 8 app

I am developing an app which uses Map service for Windows Phone 8.
I followed a link
http://themightyhedgehog.blogspot.de/2013/01/how-to-use-google-maps-in-your-own.html
and tries to develop an app containing Google Map.
But I got an error in Xaml on line
MapAppScope:BindingHelpers.TileSource="{Binding GoogleMap}"
and the error I got are:
BuildingHelpers is not supported in Silverlight.
The attachable property 'TileSource' was not found in type 'BuildingHelpers'.
The Namespace prefix "MapAppScope" is not defined.
In Xaml:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Microsoft_Phone_Controls_Maps:Map
Name="MyMap"
Grid.Column="1"
LogoVisibility="Collapsed"
d:LayoutOverrides="GridBox"
MapAppScope:BindingHelpers.TileSource="{Binding GoogleMap}"
Margin="0,0,0,2">
<Microsoft_Phone_Controls_Maps:Map.Mode>
<MSPCMCore:MercatorMode/>
</Microsoft_Phone_Controls_Maps:Map.Mode>
</Microsoft_Phone_Controls_Maps:Map>
</Grid>
In .CS:
namespace Google_Map_App
{
public enum GoogleType
{
Street = 'm',
Hybrid = 'y',
Satellite = 's',
Physical = 't',
PhysicalHybrid = 'p',
StreetOverlay = 'h',
WaterOverlay = 'r'
}
public class Google : TileSource
{
public Google()
{
MapType = GoogleType.Street;
UriFormat = #"http://mt{0}.google.com/vt/lyrs={1}&z={2}&x={3}&y={4}";
}
public GoogleType MapType { get; set; }
public override Uri GetUri(int x, int y, int zoomLevel)
{
return new Uri(
string.Format(UriFormat, (x % 2) + (2 * (y % 2)),
(char)MapType, zoomLevel, x, y));
}
}
public static class BindingHelpers
{
//Used for binding a single TileSource object to a Bing Maps control
#region TileSourceProperty
// Name, Property type, type of object that hosts the property, method to call when anything changes
public static readonly DependencyProperty TileSourceProperty =
DependencyProperty.RegisterAttached("TileSource", typeof(TileSource),
typeof(BindingHelpers), new PropertyMetadata(SetTileSourceCallback));
// Called when TileSource is retrieved
public static TileSource GetTileSource(DependencyObject obj)
{
return obj.GetValue(TileSourceProperty) as TileSource;
}
// Called when TileSource is set
public static void SetTileSource(DependencyObject obj, TileSource value)
{
obj.SetValue(TileSourceProperty, value);
}
//Called when TileSource is set
private static void SetTileSourceCallback(object sender, DependencyPropertyChangedEventArgs args)
{
var map = sender as Map;
var newSource = args.NewValue as TileSource;
if (newSource == null || map == null) return;
// Remove existing layer(s)
for (var i = map.Children.Count - 1; i >= 0; i--)
{
var tileLayer = map.Children[i] as MapTileLayer;
if (tileLayer != null)
{
map.Children.RemoveAt(i);
}
}
var newLayer = new MapTileLayer();
newLayer.TileSources.Add(newSource);
map.Children.Add(newLayer);
}
#endregion
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
}
}
Note that using Google Maps tiles in the Bing Maps WP8 or Windows 8 control is against the terms of use of both the Bing Maps and Google Maps API's. Any app found in the app store doing this will be removed.

google map load map using internet or gps

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.