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

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;
}
}

Related

Display store location via map pin in xamarin form

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.

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.

CodenameOne google maps - some markers not appearing

Using the fantastic Native Google Maps cn1lib, I'm attempting to place markers on the map, first one representing the user, then another slew of them representing objects from my database. The first marker always plunks down fine, and I can relocate it (by erasing it and creating a new one in the new position), but the subsequent markers don't show on the map. I get no errors in the simulator or on an Android device, but on both the additional markers don't show. The code looks like this:
class MyClass{
LinkedList<MapContainer.MapObject> towerMarkers;
MapContainer towerMap;
public void displayTowers(ArrayList<HashMap<String,Object>> towers){
if(towerMarkers == null){
towerMarkers = new LinkedList<>();
}else{
for(MapContainer.MapObject marker: towerMarkers){
towerMap.removeMapObject(marker);
}
towerMarkers.clear();
}
for(HashMap<String, Object> obj: towers){
towerMarkers.add(towerMap.addMarker(EncodedImage.createFromImage(FontImage.createMaterial(
FontImage.MATERIAL_SETTINGS_INPUT_ANTENNA, cellTowerMarker, 3), false),
new Coord(Double.parseDouble((String)obj.get("latitude")), Double.parseDouble((String)obj.get("longitude"))),
"", "", null));
}
}
...
The code that works is very similar:
towerMap.addTapListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
int x = evt.getX();
int y = evt.getY();
Coord tapCoord = towerMap.getCoordAtPosition(x, y);
if(myLocationMarker != null){
towerMap.removeMapObject(myLocationMarker);
}
myLocationMarker = towerMap.addMarker(EncodedImage.createFromImage(FontImage.createMaterial(FontImage.MATERIAL_LOCATION_ON, userLocationMarker, 4),
false), tapCoord, null, null, null);
findLongitudeField(f).setText(Double.toString(tapCoord.getLongitude()));
findLatitudeField(f).setText(Double.toString(tapCoord.getLatitude()));
findBtnUseChosenLocation(f).setEnabled(true);
}
});
The only odd thing that I noticed is when I inspect the map markers, they all (including the one that appears) seem to have coordinates in total different system. Instead of (35.789..., 32.1233...), they're more like (3897665.88999, 4277888.988884), but since the one that shows up is also like that, it doesn't seem to be a problem.
Any help will be appreciated!

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