Skip to main content

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.

public class GoogleMap : 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​

Instance member 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​

Instance member 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";
}

Static member 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";

Instance member 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.

Static member 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";

Instance member 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.

Instance member 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" });

Static member 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​

Instance member AddMarker(markerId, lat, lng, options, center)​

Adds a new marker to the map.

ParameterTypeDescription
markerIdStringThe unique ID that identifies the marker.
latDoubleThe latitude of the marker.
lngDoubleThe longitude of the marker.
options optionalObjectAn optional dynamic object that specifies the marker options: marker#MarkerOptions.
center optionalBooleanTrue 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);

Instance member AddMarker(markerId, location, options, center)​

Adds a new marker to the map.

ParameterTypeDescription
markerIdStringThe unique ID that identifies the marker.
locationLatLngAn instance of LatLng that identifies the location of the marker.
options optionalObjectAn optional dynamic object that specifies the marker options: marker#MarkerOptions.
center optionalBooleanTrue 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() });
}

Instance member AddMarker(markerId, address, options, center)​

Adds a new marker to the map.

ParameterTypeDescription
markerIdStringThe unique ID that identifies the marker.
addressStringThe address - to be geocoded - of the marker.
options optionalObjectAn optional dynamic object that specifies the marker options: marker#MarkerOptions.
center optionalBooleanTrue 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);

Instance member AddRoute(origin, destination, travelMode)​

Uses the Google Maps DirectionsService to route and display a path between the origin and destination. See directions.

ParameterTypeDescription
originLatLngThe latitude and longitude of the origin.
destinationLatLngThe latitude and longitude of the destination.
travelModeTravelModeThe 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);

Instance member AddRoute(origin, destination, travelMode)​

Uses the Google Maps DirectionsService to route and display a path between the origin and destination. See directions.

ParameterTypeDescription
originStringThe name of the origin.
destinationStringThe name of the destination.
travelModeTravelModeThe 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);

Instance member 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.

ParameterTypeDescription
originStringThe name of the origin.
destinationStringThe name of the destination.
travelModeTravelModeThe type of routing requested.
unitSystem optionalUnitSystem(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 optionalWaypoint[]Specifies an array of Waypoints. Waypoints alter a route by routing it through the specified location(s).
optimizeWaypoints optionalBoolean(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 optionalBoolean(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 optionalBoolean(optional) when set to true indicates that the calculated route(s) should avoid ferries, if possible.
avoidHighways optionalBoolean(optional) when set to true indicates that the calculated route(s) should avoid major highways, if possible.
avoidTolls optionalBoolean(optional) when set to true indicates that the calculated route(s) should avoid toll roads, if possible.
region optionalString(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);

Instance member 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.

ParameterTypeDescription
originLatLngThe latitude and longitude of the origin.
destinationLatLngThe latitude and longitude of the destination.
travelModeTravelModeThe type of routing requested.
unitSystem optionalUnitSystem(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 optionalWaypoint[]Specifies an array of Waypoints. Waypoints alter a route by routing it through the specified location(s).
optimizeWaypoints optionalBoolean(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 optionalBoolean(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 optionalBoolean(optional) when set to true indicates that the calculated route(s) should avoid ferries, if possible.
avoidHighways optionalBoolean(optional) when set to true indicates that the calculated route(s) should avoid major highways, if possible.
avoidTolls optionalBoolean(optional) when set to true indicates that the calculated route(s) should avoid toll roads, if possible.
region optionalString(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");

Instance member CenterMap(lat, lng)​

Centers the map at the specified location.

ParameterTypeDescription
latDoubleThe latitude of the center of the map.
lngDoubleThe 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);

Instance member CenterMap(location)​

Centers the map at the specified location.

ParameterTypeDescription
locationLatLngAn instance of LatLng than identifies 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 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);
}

Instance member CenterMap(address)​

Centers the map at the specified address.

ParameterTypeDescription
addressStringThe 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");

Instance member 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 });
}

Instance member 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);

Instance member CloseInfoWindow(markerId)​

Closes the google.maps.InfoWindow related to the specified marker.

ParameterTypeDescription
markerIdStringThe 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");

Instance member FitBounds(coordinates)​

Centers and zooms the map to fit a set of coordinates.

ParameterTypeDescription
coordinatesLatLng[]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);

Instance member GetGeocode(callback, address)​

Retrieves geocode information.

ParameterTypeDescription
callbackAction<GeocoderResult[]>The callback method.
addressStringThe 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");

Instance member GetGeocode(callback, location)​

Retrieves geocode information.

ParameterTypeDescription
callbackAction<GeocoderResult[]>The callback method.
locationLatLngThe 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);
}

Instance member GetGeocode(callback, lat, lng)​

Retrieves geocode information.

ParameterTypeDescription
callbackAction<GeocoderResult[]>The callback method.
latDoubleThe latitude.
lngDoubleThe 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);

Instance member GetGeocodeAsync(address)​

Asynchronously retrieves geocode information.

ParameterTypeDescription
addressStringThe 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);
}

Instance member GetGeocodeAsync(location)​

Asynchronously retrieves geocode information.

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

Instance member GetGeocodeAsync(lat, lng)​

Asynchronously retrieves geocode information.

ParameterTypeDescription
latDoubleThe latitude.
lngDoubleThe 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:

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

Protected member OnMapClick(e)​

Fires the Click event.

ParameterTypeDescription
eMapMouseEventArgs

Protected member OnMapDoubleClick(e)​

Fires the MapDoubleClick event.

ParameterTypeDescription
eMapMouseEventArgs

Protected member OnMapDragEnd(e)​

Fires the MapDragEnd event.

ParameterTypeDescription
eEventArgs

Protected member OnMapDragStart(e)​

Fires the MapDragStart event.

ParameterTypeDescription
eEventArgs

Protected member OnMapPropertyChanged(e)​

Fires the MapPropertyChanged event.

ParameterTypeDescription
eMapPropertyChangedEventArgs

Protected member OnMarkerDragEnd(e)​

Fires the MarkerDragEnd event.

ParameterTypeDescription
eMarkerDragEventArgs

Protected member OnMarkerDragStart(e)​

Fires the MarkerDragStart event.

ParameterTypeDescription
eMarkerDragEventArgs

Protected member OnWidgetEvent(e)​

Handles events fired by the widget.

ParameterTypeDescription
eWidgetEventArgs

Instance member RemoveMarker(markerId)​

Removes the marker.

ParameterTypeDescription
markerIdStringThe 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);
}

Instance member ShowInfoWindow(markerId, html)​

Shows an instance of the google.maps.InfoWindow class in relation to the marker.

ParameterTypeDescription
markerIdStringThe marker unique ID.
htmlStringHTML 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");
}

Instance member ShowInfoWindow(markerId, options)​

Shows an instance of the google.maps.InfoWindow class in relation to the marker.

ParameterTypeDescription
markerIdStringThe marker unique ID.
optionsObjectOptions 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​

Instance member MapClick​

MapMouseEventHandler Fired when the user clicks on the map or a marker.

Instance member MapDoubleClick​

MapMouseEventHandler Fired when the user double clicks on the map or a marker.

Instance member MapDragEnd​

EventHandler Fired when the user drags the map.

Instance member MapDragStart​

EventHandler Fired when the user starts dragging the map.

Instance member MapPropertyChanged​

MapPropertyChangedEventHandler Fired when the user changes the map by zooming, tilting, or selecting a different map type.

Instance member MarkerDragEnd​

MarkerDragEventHandler Fired when the user drags a marker.

Instance member MarkerDragStart​

MarkerDragEventHandler Fired when the user begins dragging a marker.

Implements​