How to: Draw Lines on a Map using Google Maps API
- 3 minutes to read
This example demonstrates how to draw lines that connect the map markers using an ASP.NET application created according to the Use Raster Maps tutorial.
- Add the WebPolylineController View Controller to the ASP.NET module project.
- In the constructor, set the ViewController.TargetObjectType property to IMapsMarker and the ViewController.TargetViewType to ViewType.ListView.
- Override the OnViewControlsCreated method and access the WebMapsListEditor List Editor and its MapViewer control. This control exposes the MapViewer.ClientSideEvents property, which allows you to assign JavaScript handlers to the client-side events.
- Handle the MapViewerClientSideEvents.Customize client-side event and draw a polygon line that connects the displayed markers.
- To access the markers list, use the CollectionSourceBase.List property of the ListView.CollectionSource.
using DevExpress.Persistent.Base;
using DevExpress.ExpressApp.Maps.Web;
using System.Web.Script.Serialization;
using DevExpress.ExpressApp.Maps.Web.Helpers;
// ...
public class WebPolylineController : ViewController<ListView> {
public WebPolylineController() {
TargetObjectType = typeof(IMapsMarker);
}
protected override void OnViewControlsCreated() {
base.OnViewControlsCreated();
WebMapsListEditor webMapsListEditor = ((ListView)View).Editor as WebMapsListEditor;
if (webMapsListEditor != null)
webMapsListEditor.MapViewer.ClientSideEvents.Customize = GetCustomizeScript();
}
private IEnumerable<MapPoint> GetPolylinePoints() {
List<MapPoint> polylinePoints = new List<MapPoint>();
foreach (IMapsMarker marker in View.CollectionSource.List) {
polylinePoints.Add(new MapPoint(marker.Latitude, marker.Longitude));
}
return polylinePoints;
}
private string GetCustomizeScript() {
var jsSerializer = new JavaScriptSerializer();
string polylines = jsSerializer.Serialize(GetPolylinePoints());
return string.Format(
@"function(sender, map) {{
map.on('ready', function(e) {{
var googleMap = e.originalMap;
var flightPlanCoordinates = {0};
var flightPath = new google.maps.Polyline({{
path: flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
}});
flightPath.setMap(googleMap);
}});
}}", polylines);
}
}
Run the application and create several markers. The result is demonstrated in the image below.
See Also