GoogleMap
Namespace: Wisej.Web.Ext.GoogleMaps
Assembly: Wisej.Web.Ext.GoogleMaps (4.1.0.0)
Represents an instance of the Google Maps JavaScript API map widget.
- C#
- VB.NET
public class GoogleMap : Widget
Public Class GoogleMap
Inherits Widget
A valid ApiKey is required to load the Google Maps library. The map options (map#MapOptions) are set using the dynamic Options object; the default options are zoom = 4 and center = {lat: 0, lng: 0}. Methods that change the map (markers, routes, info windows) run asynchronously on the client.
Example:
Creating a map centered on a location with a marker:
var map = new GoogleMap
{
Dock = DockStyle.Fill,
ApiKey = "YOUR_API_KEY"
};
map.Options.zoom = 12;
map.Options.mapTypeId = "roadmap";
map.Options.center = new LatLng { Lat = 40.7128, Lng = -74.0060 };
this.Controls.Add(map);
map.AddMarker("office", 40.7128, -74.0060, new { title = "Our office" });
Constructors
GoogleMap()
Initializes a new instance of the GoogleMap class.
Initializes Options with a zoom level of 4 centered at latitude 0 and longitude 0.
Properties
ApiKey
String: Returns or sets the Google Maps API key.
The key is appended to GoogleMapsURL to load the Google Maps library. When the key is empty, the library is not loaded and the widget fails to initialize with the error "Missing Google Maps API Key". Set the key before the control is rendered for the first time: the library URL is built only once per instance. See get-api-key.
Example:
Setting the API key when creating the page:
public MapPage()
{
InitializeComponent();
this.googleMap1.ApiKey = "YOUR_API_KEY";
}
GoogleMapsURL
String: Returns or sets the location of the Google Maps library. The default is //maps.googleapis.com/maps/api/js
This is a static property shared by all the sessions of the application. The query string parameters (key, v, libraries) are appended automatically and must not be included. Changing the value has no effect on maps that have already built their Packages list or after the library has been loaded in the browser.
Example:
Loading the library from a different host at application startup:
GoogleMap.GoogleMapsURL = "https://maps.googleapis.com/maps/api/js";
InitScript
String: Returns the initialization script that creates the google.maps.Map instance on the client.
The script is generated from the embedded startup.js resource and includes the serialized Options.
Libraries
String: Returns or sets the additional Google Maps libraries to load.
This is a static property shared by all the sessions of the application. The value is a comma-separated list of library names passed to the library URL as the "libraries" parameter. Set it before the first GoogleMap is rendered. See: libraries.
Example:
Loading the places and geometry libraries at application startup:
GoogleMap.Libraries = "places,geometry";
Packages
List<Package>: Returns the list of packages (scripts) to load before the widget is initialized.
Contains the Google Maps library, loaded from GoogleMapsURL with the ApiKey, Version and Libraries parameters. The list is empty when ApiKey is not set. It's built the first time it's accessed and it's not rebuilt when these properties change.
SuppressMarkers
Boolean: Returns or sets whether the default markers at the beginning and end of the routes are suppressed. (Default: False)
When true, routes created using AddRoute and the other AddRoute overloads are rendered without the default A and B markers. Markers created using AddMarker are not affected. Set this property before calling AddRoute: to change it for a route that is already displayed, call ClearRoutes and add the route again.
Example:
Displaying a route using custom markers for the origin and destination:
this.googleMap1.SuppressMarkers = true;
this.googleMap1.AddRoute("Boston, MA", "New York, NY", TravelMode.Driving);
this.googleMap1.AddMarker("start", "Boston, MA", new { title = "Start" });
this.googleMap1.AddMarker("end", "New York, NY", new { title = "End" });
Version
String: Returns or sets the Google Maps version to load.
This is a static property shared by all the sessions of the application. When set, it's passed to the library URL as the "v" parameter, i.e. "weekly", "quarterly", "beta" or a specific version number. When null or empty, Google loads its default version. Set it before the first GoogleMap is rendered. See: versions.
Example:
Selecting the release channel at application startup:
GoogleMap.Version = "quarterly";
Methods
AddMarker(markerId, lat, lng, options, center)
Adds a new marker to the map.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The unique ID that identifies the marker. |
| lat | Double | The latitude of the marker. |
| lng | Double | The longitude of the marker. |
| options | Object | An optional dynamic object that specifies the marker options: marker#MarkerOptions. |
| center | Boolean | True to center the map after setting the marker. |
A marker with the same markerId is replaced. Clicking the marker fires MapClick (or MapDoubleClick) with Marker set to markerId . The MarkerDragStart and MarkerDragEnd events are fired only when the options include draggable = true.
Example:
Adding a draggable marker and centering the map on it:
this.googleMap1.AddMarker("pin1", 48.8584, 2.2945, new { title = "Eiffel Tower", draggable = true }, true);
AddMarker(markerId, location, options, center)
Adds a new marker to the map.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The unique ID that identifies the marker. |
| location | LatLng | An instance of LatLng that identifies the location of the marker. |
| options | Object | An optional dynamic object that specifies the marker options: marker#MarkerOptions. |
| center | Boolean | True to center the map after setting the marker. |
A marker with the same markerId is replaced. Clicking the marker fires MapClick (or MapDoubleClick) with Marker set to markerId . The MarkerDragStart and MarkerDragEnd events are fired only when the options include draggable = true.
Example:
Adding a marker where the user clicks on the map:
private void googleMap1_MapClick(object sender, MapMouseEventArgs e)
{
if (e.Marker == null)
this.googleMap1.AddMarker("pin" + (++this.pinCount), e.Location, new { label = this.pinCount.ToString() });
}
AddMarker(markerId, address, options, center)
Adds a new marker to the map.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The unique ID that identifies the marker. |
| address | String | The address - to be geocoded - of the marker. |
| options | Object | An optional dynamic object that specifies the marker options: marker#MarkerOptions. |
| center | Boolean | True to center the map after setting the marker. |
The address is geocoded on the client using google.maps.Geocoder and the marker is placed at the first result. If geocoding fails, the browser shows an alert with the failure status and no marker is added. A marker with the same markerId is replaced.
Example:
Adding a marker at an address:
this.googleMap1.AddMarker("hq", "1600 Amphitheatre Parkway, Mountain View, CA", new { title = "Headquarters" }, true);
AddRoute(origin, destination, travelMode)
Uses the Google Maps DirectionsService to route and display a path between the origin and destination. See directions.
| Parameter | Type | Description |
|---|---|---|
| origin | LatLng | The latitude and longitude of the origin. |
| destination | LatLng | The latitude and longitude of the destination. |
| travelMode | TravelMode | The type of routing requested. |
The route is calculated on the client by google.maps.DirectionsService and displayed by a single google.maps.DirectionsRenderer: adding a new route replaces the one currently displayed. If the Directions service fails to find a route, nothing is displayed and no error is reported to the server. Use SuppressMarkers to hide the default markers at the beginning and end of the route.
Example:
Displaying a walking route between two coordinates:
var origin = new LatLng { Lat = 51.5007, Lng = -0.1246 };
var destination = new LatLng { Lat = 51.5081, Lng = -0.0759 };
this.googleMap1.AddRoute(origin, destination, TravelMode.Walking);
AddRoute(origin, destination, travelMode)
Uses the Google Maps DirectionsService to route and display a path between the origin and destination. See directions.
| Parameter | Type | Description |
|---|---|---|
| origin | String | The name of the origin. |
| destination | String | The name of the destination. |
| travelMode | TravelMode | The type of routing requested. |
The route is calculated on the client by google.maps.DirectionsService and displayed by a single google.maps.DirectionsRenderer: adding a new route replaces the one currently displayed. If the Directions service fails to find a route, nothing is displayed and no error is reported to the server. Use SuppressMarkers to hide the default markers at the beginning and end of the route.
Example:
Displaying a driving route between two addresses:
this.googleMap1.AddRoute("San Francisco, CA", "Los Angeles, CA", TravelMode.Driving);
AddRoute(origin, destination, travelMode, unitSystem, waypoints, optimizeWaypoints, provideRouteAlternatives, avoidFerries, avoidHighways, avoidTolls, region)
Uses the Google Maps DirectionsService to route and display a path between the origin and destination. See directions.
| Parameter | Type | Description |
|---|---|---|
| origin | String | The name of the origin. |
| destination | String | The name of the destination. |
| travelMode | TravelMode | The type of routing requested. |
| unitSystem | UnitSystem | (optional) Specifies what unit system to use when displaying results. Note: This unit system setting only affects the text displayed to the user. The directions result (returned by google maps API) also contains distance values, not shown to the user, which are always expressed in meters. |
| waypoints | Waypoint[] | Specifies an array of Waypoints. Waypoints alter a route by routing it through the specified location(s). |
| optimizeWaypoints | Boolean | (optional) specifies that the route using the supplied waypoints may be optimized by rearranging the waypoints in a more efficient order. If true, the Directions service will return the reordered waypoints in a waypoint_order field. |
| provideRouteAlternatives | Boolean | (optional) when set to true specifies that the Directions service may provide more than one route alternative in the response. Note that providing route alternatives may increase the response time from the server. This is only available for requests without intermediate waypoints. |
| avoidFerries | Boolean | (optional) when set to true indicates that the calculated route(s) should avoid ferries, if possible. |
| avoidHighways | Boolean | (optional) when set to true indicates that the calculated route(s) should avoid major highways, if possible. |
| avoidTolls | Boolean | (optional) when set to true indicates that the calculated route(s) should avoid toll roads, if possible. |
| region | String | (optional) Return results biased to a particular region. This parameter takes a region code, specified as a two-character (non-numeric) Unicode region subtag. |
The route is calculated on the client by google.maps.DirectionsService and displayed by a single google.maps.DirectionsRenderer: adding a new route replaces the one currently displayed. If the Directions service fails to find a route, nothing is displayed and no error is reported to the server. Use SuppressMarkers to hide the default markers at the beginning and end of the route.
Example:
Displaying a route through two waypoints, avoiding tolls and using miles:
var waypoints = new[]
{
new Waypoint("Philadelphia, PA", true),
new Waypoint("Baltimore, MD", false)
};
this.googleMap1.AddRoute(
"New York, NY",
"Washington, DC",
TravelMode.Driving,
UnitSystem.Imperial,
waypoints,
avoidTolls: true);
AddRoute(origin, destination, travelMode, unitSystem, waypoints, optimizeWaypoints, provideRouteAlternatives, avoidFerries, avoidHighways, avoidTolls, region)
Uses the Google Maps DirectionsService to route and display a path between the origin and destination. See directions.
| Parameter | Type | Description |
|---|---|---|
| origin | LatLng | The latitude and longitude of the origin. |
| destination | LatLng | The latitude and longitude of the destination. |
| travelMode | TravelMode | The type of routing requested. |
| unitSystem | UnitSystem | (optional) Specifies what unit system to use when displaying results. Note: This unit system setting only affects the text displayed to the user. The directions result (returned by google maps API) also contains distance values, not shown to the user, which are always expressed in meters. |
| waypoints | Waypoint[] | Specifies an array of Waypoints. Waypoints alter a route by routing it through the specified location(s). |
| optimizeWaypoints | Boolean | (optional) specifies that the route using the supplied waypoints may be optimized by rearranging the waypoints in a more efficient order. If true, the Directions service will return the reordered waypoints in a waypoint_order field. |
| provideRouteAlternatives | Boolean | (optional) when set to true specifies that the Directions service may provide more than one route alternative in the response. Note that providing route alternatives may increase the response time from the server. This is only available for requests without intermediate waypoints. |
| avoidFerries | Boolean | (optional) when set to true indicates that the calculated route(s) should avoid ferries, if possible. |
| avoidHighways | Boolean | (optional) when set to true indicates that the calculated route(s) should avoid major highways, if possible. |
| avoidTolls | Boolean | (optional) when set to true indicates that the calculated route(s) should avoid toll roads, if possible. |
| region | String | (optional) Return results biased to a particular region. This parameter takes a region code, specified as a two-character (non-numeric) Unicode region subtag. |
The route is calculated on the client by google.maps.DirectionsService and displayed by a single google.maps.DirectionsRenderer: adding a new route replaces the one currently displayed. If the Directions service fails to find a route, nothing is displayed and no error is reported to the server. Use SuppressMarkers to hide the default markers at the beginning and end of the route.
Example:
Displaying a bicycling route in kilometers that avoids highways:
var origin = new LatLng { Lat = 52.3676, Lng = 4.9041 };
var destination = new LatLng { Lat = 52.0907, Lng = 5.1214 };
this.googleMap1.AddRoute(origin, destination, TravelMode.Bicycling, UnitSystem.Metric, avoidHighways: true, region: "nl");
CenterMap(lat, lng)
Centers the map at the specified location.
| Parameter | Type | Description |
|---|---|---|
| lat | Double | The latitude of the center of the map. |
| lng | Double | The longitude of the center of the map. |
The zoom level is not changed. To also change the zoom level, set Options.zoom.
Example:
Centering the map on a location:
this.googleMap1.CenterMap(35.6762, 139.6503);
CenterMap(location)
Centers the map at the specified location.
The zoom level is not changed. To also change the zoom level, set Options.zoom.
Example:
Centering the map on a geocoded result:
private async void buttonSydney_Click(object sender, EventArgs e)
{
var results = await this.googleMap1.GetGeocodeAsync("Sydney Opera House");
if (results.Length > 0 && !results[0].IsError)
this.googleMap1.CenterMap(results[0].GeocodeGeometry.Location);
}
CenterMap(address)
Centers the map at the specified address.
| Parameter | Type | Description |
|---|---|---|
| address | String | The address - to be geocoded - of the new center of the map. |
The address is geocoded on the client using google.maps.Geocoder and the map is centered at the first result. If geocoding fails, the browser shows an alert with the failure status. The zoom level is not changed.
Example:
Centering the map on an address:
this.googleMap1.CenterMap("Piazza San Marco, Venice, Italy");
ClearMarkers()
Removes all the markers from the map.
Only the markers added with AddMarker are removed; the markers of a route are removed by ClearRoutes.
Example:
Replacing all the markers with a new set of locations:
this.googleMap1.ClearMarkers();
foreach (var store in stores)
{
this.googleMap1.AddMarker(store.Id, store.Latitude, store.Longitude, new { title = store.Name });
}
ClearRoutes()
Clears any routes, if they exist.
Removes the route displayed by the AddRoute methods, including its default markers. Markers added with AddMarker are not affected.
Example:
Removing the current route before showing a new one:
this.googleMap1.ClearRoutes();
this.googleMap1.AddRoute("Milan, Italy", "Rome, Italy", TravelMode.Driving);
CloseInfoWindow(markerId)
Closes the google.maps.InfoWindow related to the specified marker.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The marker unique ID. |
Nothing happens if the marker doesn't exist or its info window has never been shown.
Example:
Closing the info window of a marker:
this.googleMap1.CloseInfoWindow("office");
FitBounds(coordinates)
Centers and zooms the map to fit a set of coordinates.
| Parameter | Type | Description |
|---|---|---|
| coordinates | LatLng[] | The coordinates that must be visible on the map. |
Sets the viewport (center and zoom level) so that all the coordinates are visible. The map must already be initialized on the client when this method is called.
Example:
Showing all the markers on the map:
var rome = new LatLng { Lat = 41.9028, Lng = 12.4964 };
var paris = new LatLng { Lat = 48.8566, Lng = 2.3522 };
this.googleMap1.AddMarker("rome", rome);
this.googleMap1.AddMarker("paris", paris);
this.googleMap1.FitBounds(rome, paris);
GetGeocode(callback, address)
Retrieves geocode information.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<GeocoderResult[]> | The callback method. |
| address | String | The address. |
The request is processed asynchronously on the client using google.maps.Geocoder: callback is invoked when the response is received. If the request fails, the array contains a single GeocoderResult with IsError set to true and ResultCode set to the status returned by Google, i.e. "ZERO_RESULTS". Pending requests are identified by the hash code of callback : issuing a second request with the same delegate instance before the first one completes replaces the first callback.
Example:
Showing the coordinates of an address:
this.googleMap1.GetGeocode(results =>
{
if (results.Length > 0 && !results[0].IsError)
AlertBox.Show(results[0].GeocodeGeometry.Location.ToString());
}, "10 Downing Street, London");
GetGeocode(callback, location)
Retrieves geocode information.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<GeocoderResult[]> | The callback method. |
| location | LatLng | The location (latitude/longitude). |
The request is processed asynchronously on the client using google.maps.Geocoder: callback is invoked when the response is received. If the request fails, the array contains a single GeocoderResult with IsError set to true and ResultCode set to the status returned by Google, i.e. "ZERO_RESULTS". Pending requests are identified by the hash code of callback : issuing a second request with the same delegate instance before the first one completes replaces the first callback.
Example:
Showing the address of the location clicked by the user:
private void googleMap1_MapClick(object sender, MapMouseEventArgs e)
{
this.googleMap1.GetGeocode(results =>
{
if (results.Length > 0 && !results[0].IsError)
AlertBox.Show(results[0].FormattedAddress);
}, e.Location);
}
GetGeocode(callback, lat, lng)
Retrieves geocode information.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<GeocoderResult[]> | The callback method. |
| lat | Double | The latitude. |
| lng | Double | The longitude. |
The request is processed asynchronously on the client using google.maps.Geocoder: callback is invoked when the response is received. If the request fails, the array contains a single GeocoderResult with IsError set to true and ResultCode set to the status returned by Google, i.e. "ZERO_RESULTS". Pending requests are identified by the hash code of callback : issuing a second request with the same delegate instance before the first one completes replaces the first callback.
Example:
Reading the country of a location:
this.googleMap1.GetGeocode(results =>
{
foreach (var component in results[0].AddressComponents ?? new GeocoderResult.AddressComponent[0])
{
if (Array.IndexOf(component.Types, "country") > -1)
this.labelCountry.Text = component.LongName;
}
}, 45.4642, 9.1900);
GetGeocodeAsync(address)
Asynchronously retrieves geocode information.
| Parameter | Type | Description |
|---|---|---|
| address | String | The address. |
Returns: Task<GeocoderResult[]>. A task that completes with the array of GeocoderResult objects returned by the geocoder.
The request is processed on the client using google.maps.Geocoder. If the request fails, the array contains a single GeocoderResult with IsError set to true and ResultCode set to the status returned by Google, i.e. "ZERO_RESULTS". The task doesn't complete if the client doesn't respond, for example when the Google Maps library has not been loaded.
Example:
Geocoding an address entered by the user:
private async void buttonSearch_Click(object sender, EventArgs e)
{
var results = await this.googleMap1.GetGeocodeAsync(this.textBoxAddress.Text);
if (results.Length == 0 || results[0].IsError)
{
AlertBox.Show("Address not found.");
return;
}
var location = results[0].GeocodeGeometry.Location;
this.googleMap1.AddMarker("search", location, null, true);
}
GetGeocodeAsync(location)
Asynchronously retrieves geocode information.
| Parameter | Type | Description |
|---|---|---|
| location | LatLng | The location (latitude/longitude). |
Returns: Task<GeocoderResult[]>. A task that completes with the array of GeocoderResult objects returned by the geocoder.
The request is processed on the client using google.maps.Geocoder. If the request fails, the array contains a single GeocoderResult with IsError set to true and ResultCode set to the status returned by Google, i.e. "ZERO_RESULTS". The task doesn't complete if the client doesn't respond, for example when the Google Maps library has not been loaded.
Example:
Showing the address of a marker after it has been dragged:
private async void googleMap1_MarkerDragEnd(object sender, MarkerDragEventArgs e)
{
var results = await this.googleMap1.GetGeocodeAsync(e.Location);
if (results.Length > 0 && !results[0].IsError)
this.textBoxAddress.Text = results[0].FormattedAddress;
}
GetGeocodeAsync(lat, lng)
Asynchronously retrieves geocode information.
Returns: Task<GeocoderResult[]>. A task that completes with the array of GeocoderResult objects returned by the geocoder.
The request is processed on the client using google.maps.Geocoder. If the request fails, the array contains a single GeocoderResult with IsError set to true and ResultCode set to the status returned by Google, i.e. "ZERO_RESULTS". The task doesn't complete if the client doesn't respond, for example when the Google Maps library has not been loaded.
Example:
Reverse geocoding a set of coordinates:
private async void buttonLookup_Click(object sender, EventArgs e)
{
var results = await this.googleMap1.GetGeocodeAsync(40.6892, -74.0445);
if (results.Length > 0 && !results[0].IsError)
this.labelAddress.Text = results[0].FormattedAddress;
}
OnMapClick(e)
Fires the Click event.
| Parameter | Type | Description |
|---|---|---|
| e | MapMouseEventArgs |
OnMapDoubleClick(e)
Fires the MapDoubleClick event.
| Parameter | Type | Description |
|---|---|---|
| e | MapMouseEventArgs |
OnMapDragEnd(e)
Fires the MapDragEnd event.
| Parameter | Type | Description |
|---|---|---|
| e | EventArgs |
OnMapDragStart(e)
Fires the MapDragStart event.
| Parameter | Type | Description |
|---|---|---|
| e | EventArgs |
OnMapPropertyChanged(e)
Fires the MapPropertyChanged event.
| Parameter | Type | Description |
|---|---|---|
| e | MapPropertyChangedEventArgs |
OnMarkerDragEnd(e)
Fires the MarkerDragEnd event.
| Parameter | Type | Description |
|---|---|---|
| e | MarkerDragEventArgs |
OnMarkerDragStart(e)
Fires the MarkerDragStart event.
| Parameter | Type | Description |
|---|---|---|
| e | MarkerDragEventArgs |
OnWidgetEvent(e)
Handles events fired by the widget.
| Parameter | Type | Description |
|---|---|---|
| e | WidgetEventArgs |
RemoveMarker(markerId)
Removes the marker.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The unique ID of the marker to remove. |
Nothing happens if a marker with the specified ID doesn't exist.
Example:
Removing a marker when the user right-clicks it:
private void googleMap1_MapClick(object sender, MapMouseEventArgs e)
{
if (e.Marker != null && e.Button == MouseButtons.Right)
this.googleMap1.RemoveMarker(e.Marker);
}
ShowInfoWindow(markerId, html)
Shows an instance of the google.maps.InfoWindow class in relation to the marker.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The marker unique ID. |
| html | String | HTML content to display in the info window. |
The google.maps.InfoWindow is created the first time it's shown for a marker and it's reused afterwards: calling this method again for the same marker reopens the existing window without changing its content. To display different content, add the marker again with AddMarker before showing the info window. Nothing happens if the marker doesn't exist.
Example:
Showing an info window when the user clicks a marker:
private void googleMap1_MapClick(object sender, MapMouseEventArgs e)
{
if (e.Marker == "office")
this.googleMap1.ShowInfoWindow(e.Marker, "<b>Head Office</b><br/>Open 9:00 - 17:00");
}
ShowInfoWindow(markerId, options)
Shows an instance of the google.maps.InfoWindow class in relation to the marker.
| Parameter | Type | Description |
|---|---|---|
| markerId | String | The marker unique ID. |
| options | Object | Options for the creation of the InfoWindow. See infowindows. |
The google.maps.InfoWindow is created the first time it's shown for a marker and it's reused afterwards: calling this method again for the same marker reopens the existing window and ignores the new options . Nothing happens if the marker doesn't exist.
Example:
Showing an info window with a maximum width:
this.googleMap1.ShowInfoWindow("office", new
{
content = "<b>Head Office</b><br/>123 Main Street",
maxWidth = 200
});
Events
MapClick
MapMouseEventHandler Fired when the user clicks on the map or a marker.
MapDoubleClick
MapMouseEventHandler Fired when the user double clicks on the map or a marker.
MapDragEnd
EventHandler Fired when the user drags the map.
MapDragStart
EventHandler Fired when the user starts dragging the map.
MapPropertyChanged
MapPropertyChangedEventHandler Fired when the user changes the map by zooming, tilting, or selecting a different map type.
MarkerDragEnd
MarkerDragEventHandler Fired when the user drags a marker.
MarkerDragStart
MarkerDragEventHandler Fired when the user begins dragging a marker.