Display store location via map pin in xamarin form - google-maps

I want to expound the title. Currently we are making our thesis/project.
We have 2 platforms. Web and mobile.
In our web, we have functionality/feature that admin can insert data of store into database, example fields are name of the store, their products and the LOCATION OF that store.
I am assign in our mobile, one of the functionality is map. I have this UI
That red circle is the parameter of our location or limitation or let say NEARBY ME and the PINS assuming those are the store who subscribes in our system, that's my expected output.
This is what I've done in my tab view "map" with map.
my map xaml
<maps:Map
x:Name="myMap"
MapType="Hybrid"
IsShowingUser="True"
/>
map.xaml.cs
public MapPage()
{
InitializeComponent();
DisplayCurrentLocation();
// this.AddMarkerInCurrentLocation();
}
public async void DisplayCurrentLocation()
{
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Medium);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
Position p = new Position(location.Latitude, location.Longitude);
MapSpan mapSpan = MapSpan.FromCenterAndRadius(p, Distance.FromKilometers(.444));
myMap.MoveToRegion(mapSpan);
}
}
catch(FeatureNotSupportedException fnsEx)
{
}
catch
(FeatureNotEnabledException fneEx)
{
}
catch(Exception ex)
{
}
}
Any link's solution that are related to my post, kindly comment it and Im glad to study the article. Thank you in advance.

Display store location via map pin in xamarin form
If you have obtained the location(Latitude, Longitude) of the stores, you can do this:
List<Location_Store> Location_Stores =new List<Location_Store>();
// Add the location of stores to List
Location_Stores.add(...);
foreach (var item in Location_Stores)            
{                
Pin pin = new Pin                
{                    
Label = item.StoreName,                    
//Address = "The city with a boardwalk",                    
Type = PinType.Place,                    
Position = new Position(item.Latitude,item.Longitude)               
};                
myMap.Pins.Add(pin);            
}
Location_Store.cs:
public class Location_Store    
{        
public string StoreName { get; set; }        
public double Latitude { get; set; }        
public double Longitude { get; set; }
...    
}
For more information about how to display location by pin in Xamarin Forms, you can refer to Xamarin.Forms Map Pins.

Related

Fetching Contacts From People Hub

I am building a Windows Phone 8 application. For that I require to fetch contacts from People Hub App. Is there any way I can keep these contacts even after the application closes?
I have looked into data caching but if the contact has been updated then caching won't work.
This can be done.
I've implemented this with the Group Contacts app.
In my solution, I used SQLite to store contacts into various categories based on user preference.
When the app starts up, I initialize my local database using SQLite and pull contacts from there as well as retrieving all the contacts the phone itself.
Example:
await ContactsRepository.Instance.Initialize();
var appContacts = await ContactsRepository.Instance.Get();
var phoneContacts = await ContactServices.Instance.LoadContacts(Contacts, SelectedCategory);
MergeContacts(appContacts, phoneContacts);
.
.
When ever the app starts up, it needs to create a database if one does not already exist.
Example:
public async Task Initialize()
{
_connection = new SQLiteAsyncConnection(Constants.DATABASE_FILE_NAME);
await EnsureTableExist<ContactReference>(_connection);
}
private async Task EnsureTableExist<T>(SQLiteAsyncConnection connection) where T : new()
{
bool noTableExists = false;
try
{
var query = await connection.Table<T>().FirstOrDefaultAsync();
}
catch (SQLiteException ex)
{
if (ex.Message.Contains("no such table"))
{
noTableExists = true;
}
}
if (noTableExists)
{
await connection.CreateTableAsync<T>();
}
}
Windows 8.1 uses a ContactManager to retrieve contacts from the People Hub.
Example:
public async Task<ObservableCollection<Contact>> LoadContacts(ObservableCollection<Contact> contacts, Category category)
{
contacts.Clear();
try
{
var contactStore = await ContactManager.RequestStoreAsync();
var result = await contactStore.FindContactsAsync();
foreach (var item in result)
{
contacts.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return contacts;
}
Then I manage my contact collection between the phone's contact list and my app's contact list.
Example:
private void MergeContacts(ObservableCollection<ContactReference> appContacts, ObservableCollection<Contact> phoneContacts)
{
foreach (var contact in phoneContacts)
{
var contactExists = appContacts.Any(c => c.ContactId == contact.Id);
if (!contactExists)
{
OthersCategory.Contacts.Add(contact);
}
Category category = GetCategory(contact);
if (category == null)
{
OthersCategory.Contacts.Add(contact);
}
}
SortContacts(OthersCategory);
}
I created an entity class to support my local database operations.
Example:
public class ContactReference
{
[PrimaryKey]
public string ContactId { get; set; }
public string CategoryName { get; set; }
}
NOTE:
The emulator that VS2013 provides does not have a list of imaginary contacts.
As a result, I found testing easier by using my personal phone for debugging.

Binding doesn't work in MVVM in WP8

I am new in the development of WP8. I have been following a online course for a couple of weeks and the second task of the course was to develop a app to show the weather, some news and photos related to the city.
So far, I have develop the app following the MVVM pattern using the Panorama control as the conteiner for the differents contents I need to show.
To no longer this, the problem I facing is at the moment to display the xml data that is retrieve from the webservices.
The XAML is:
<phone:panorama x:Name="myPanorama"
DataContext = {Binding Source="WeatherViewModel"}>
<PanoramaItem header="MyWeather">
<Textblock x:name="txtCity"
Text = {Binding Weather.City}
</Textblock>
</PanoramaItem>
<panoramaItem header="Config">
<Text x:Name="txtGetCity"/>
<Button x:Name="btnGetCity"
Command={Binding GetWeatherCommand}/>
</panoramaItem>
</phone:panorama>
My ViewModel:
public class WeaterViewModel : NotificationEnableObject
{
private Weather _currentWeather;
public Weather GetCurrentWeather
{
get
{
if (_currentWeather == null)
_currentWeather = new Weather();
return _currentWeather;
}
set { _currentWeather = value;
OnPropertyChanged("GetCurrentWeather");
}
}
//Constructor ServiceModel serviceModel = new ServiceModel();
public WeatherViewModel()
{
serviceModel.GetWeatherCompleted += (s, a) =>
{
_currentWeather = new Clima();
_currentWeather.City= a.Results[0].City;
_currentWeather.tempC = a.Results[0].tempC;
};
getWeatherCommand = new ActionCommand(null);
}
ActionCommand getWeatherCommand; // ActionCommand derivied from ICommand
public ActionCommand GetWeatherCommand
{
get
{
if (getWeatherCommand!= null)
{
getWeatherCommand = new ActionCommand(() =>
{
//Call the Service who retrieved the data
});
}
return getWeatherCommand;
}
}
}
The Weather specified is a public class which contain the City property. I have tried using an IObservableCollention as well howerver, the result is the same :-(
As you can see in the panorama control I have 2 sections. The one where I write the city I wanna see and the section where I show the information I get from the web services.
Any clue, or help would be very appreciate
Regards!
Ok, I think that is an easy fix.
You're setting GetCurrentWeather this way:
_currentWeather = new Clima();
_currentWeather.City= a.Results[0].City;
_currentWeather.tempC = a.Results[0].tempC;
This is not firing the PropertyChanged event. Change it to:
GetCurrentWeather= new Clima();
GetCurrentWeather.City= a.Results[0].City;
GetCurrentWeather.tempC = a.Results[0].tempC;
and you should be fine.

How to implement google maps to search by street name, city?

I need search functionality like this site. But I am wondering how can I get coordinates from google api by street name?
Google Geocoding API
You can enter in an address and it will return the Lat/long co-ordinates in a Json response or XML etc
You can read about it here:
http://code.google.com/apis/maps/documentation/geocoding/
In the onclick event of search write
List<Address> addresses = geoCoder.getFromLocationName("enter location name",5);
p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = map.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
map.invalidate();
Then create map overlay class in mapActivity
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw()
{
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}

BlackBerry and map based apps like Yelp and Google Map

This is a question-loaded post from someone who is just getting started with BB development. Any guidance is much appreciated.
How are map based BlackBerry apps such as Yelp and Google Map implemented? As with the web based version. Yelp for the BB allows you to search for restaurants & etc. based on on the current or specified location. The search result is in a form of a list or a map view displaying markers of the search results. Yelp's map is powered by Bing. How is the map, along with the markers, invoked within the BB code? For the list view, what is being used to retrieve the list of results from the database. Can any database be used?
Google Map 3.2 for the BB now supports layers. Again, how are the Google maps invoked? You can also select a marker (i.e. Wiki, gas station) of a particular location directly on the map and view the information of that location (i.e. Wiki, gas station address). How is this being done?
My knowledge in map technology as well as BB development is very limited, so basic or in depth feedback are both welcomed.
I have no experience of writing real-world gps applications for blackberry, below are just my observations and thoughts about possible workarounds.
Blackberry Yelp Application
Indeed, Blackberry Yelp application show map if you do search and then go into result and see Map Adress
alt text http://img197.imageshack.us/img197/965/13428830.jpgalt text http://img269.imageshack.us/img269/1976/92068364.jpg
See also Yelp Launches Bing-Powered Blackberry App
If you look into Yelp API you will find only search functionality which may optionally use Google Maps to display search result location on your website.
Bing seems to be MS analogue for Google Maps. And there is an ASP Bing Map Control which hardly can be used in BB development.
Blackberry Google Maps Application
alt text http://img193.imageshack.us/img193/9678/39917026.jpg
You can invoke installed Google Maps Mobile from code:
class Scr extends MainScreen {
public Scr() {
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(mInvokeGMaps);
}
MenuItem mInvokeGMaps = new MenuItem("Run GMaps", 0, 0) {
public void run() {
GMLocation location
= new GMLocation(51.507778, -0.128056, "London");
invokeGMaps(location);
};
};
public void invokeGMaps(GMLocation l) {
int mh = CodeModuleManager.getModuleHandle("GoogleMaps");
if (mh == 0) {
try {
throw new ApplicationManagerException(
"GoogleMaps isn't installed");
} catch (ApplicationManagerException e) {
System.out.println(e.getMessage());
}
}
URLEncodedPostData uepd = new URLEncodedPostData(null, false);
uepd.append("action", "LOCN");
uepd.append("a", "#latlon:" + l.getLatitude()
+ "," + l.getLongitude());
uepd.append("title", l.getName());
uepd.append("description", l.getDescription());
String[] args = { "http://gmm/x?" + uepd.toString() };
ApplicationDescriptor ad = CodeModuleManager
.getApplicationDescriptors(mh)[0];
ApplicationDescriptor ad2 = new ApplicationDescriptor(ad, args);
try {
ApplicationManager.getApplicationManager()
.runApplication(ad2, true);
} catch (ApplicationManagerException e) {
System.out.println(e.getMessage());
}
}
}
Using custom location class:
class GMLocation {
String mName;
String mDescription;
double mLatitude;
double mLongitude;
public GMLocation(double lat, double lon) {
mLatitude = lat;
mLongitude = lon;
}
public GMLocation(double d, double e, String name) {
this(d, e);
mName = name;
}
public GMLocation(double lat, double lon, String name, String descr) {
this(lat, lon, name);
mDescription = descr;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
public String getLongitude() {
return String.valueOf(mLongitude);
}
public String getLatitude() {
return String.valueOf(mLatitude);
}
}
See also How to use Google Map in Blackberry application?
Conclusion
Blackberry browser and BrowserField has a limited support of JavaScript. Since both Bing and GMaps are based on JavaScript, my suspicion is that they use static images retrieved from server to display map control. This may be possible but that means server side implementation and all required API developer keys.
As an alternative, you can invoke installed GMaps from code on Blackberry.

How to add a dynamic Google Map to my site?

I am developing travel portal for India in which i want to add Google Maps of each hotel which is saved in the database. My problem is how do I create the map dynamically?
This is probably the best place to start:
http://code.google.com/apis/maps/documentation/introduction.html
The following is a basic example using ASP.MVC for displaying a number of Hotels on a Google Map.
The domain object is Hotel:
public class Hotel
{
public string Name { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
}
You will need a repository to get some hotel objects. Use this in the Home controller in a method called HotelsForMap():
public ActionResult HotelsForMap()
{
var hotels= new HotelRepository().GetHotels();
return Json(hotels);
}
Create a partial view for the google map. Lets call it GoogleMap. It will need to contain:
Reference to the google map api
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA" type="text/javascript"></script>
jQuery to get Hotel objects from JSON call above
$(document).ready(function(){
if (GBrowserIsCompatible())
{
$.getJSON("/Home/HotelsForMap", initialize);
}
});
jQuery to initialise map
function initialize(mapData) {
var map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new google.maps.SmallMapControl());
map.addControl(new google.maps.MapTypeControl());
var zoom = mapData.Zoom;
map.setCenter(new GLatLng(mapData[0].Latitude, mapData[0].Longitude), 8);
$.each(mapData, function(i, Hotel) {
setupLocationMarker(map, Hotel);
});
}
jQuery to set markers for hotels on the map
function setupLocationMarker(map, Hotel)
{
var latlng = new GLatLng(Hotel.Latitude, Hotel.Longitude);
var marker = new GMarker(latlng);
map.addOverlay(marker);
}
Finally, you will need a view that contains the partial view above. The view will need to have a div with an id of map_canvas as that is what is referenced in the initialize function above. The view should contain the following:
<h2>Hotels</h2>
<br />
<div id="map_canvas" style="width: 500; height: 500px">
<% Html.RenderPartial("GoogleMap"); %>
</div>
Hopefully you can use some of this, even if you are not familiar with ASP.MVC.
Check out this example:
http://blog.sofasurfer.ch/2011/06/27/dynamic-google-map-markers-via-simple-json-file/
It dynamically adds google map markers to a jSon file using google geocoder