Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use javascript to add shapes to Map API

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use javascript to add shapes to map API". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use javascript to add shapes to map API".

Brief introduction

You can add various shapes to your map. A shape is an object on a map that is bound to a latitude / longitude coordinate. The available shapes are: line, polygon, circle, and rectangle. You can also configure shapes to be edited or dragged by users.

Polyline

To draw lines on a map, use polylines. The Polyline class defines linearly connected segment overlays on the map. The Polyline object contains an array of LatLng positions, and it creates a series of segments that connect these locations in an orderly manner.

1. Add polylin

The Polyline constructor takes a set of PolylineOptions to specify the LatLng coordinates of the line, and a set of styles to adjust the visual behavior of the Polyline.

The Polyline object is drawn as a series of straight line segments on the map. You can specify a custom color, weight, and opacity for line strokes within PolylineOptions when building lines, or you can change these properties after building. Polylines support the following stroke styles:

StrokeColor specifies the hexadecimal HTML color in "# FFFFFF" format. The Polyline class does not support named colors.

StrokeOpacity specifies a value between 0.0 and 1.0 that determines the opacity of the line color. The default value is 1.0.

StrokeWeight specifies the width of the line in pixels.

The editable property of the Polyline specifies whether you can edit the shape. See user editable shapes below. Similarly, you can also allow users to drag lines by setting the draggable property.

/ / this example creates a path shown by the 2-pixel-wide red line. William's * flights across the Pacific Ocean via Auckland, CA, Brisbane, Australia. Unction initMap () {var map = new google.maps.Map (document.getElementById ('map'), {zoom: 3, center: {lat: 0, lng:-180}, mapTypeId: google.maps.MapTypeId.TERRAIN}) Var flightPlanCoordinates = [{lat: 37.772, lng:-122.214}, {lat: 21.291, lng:-157.821}, {lat:-18.142, lng: 178.431}, {lat:-27.467, lng: 153.027}]; var flightPath = new google.maps.Polyline ({path: flightPlanCoordinates, geodesic: true, strokeColor:'# FF0000', strokeOpacity: 21.291, strokeWeight: 2}) FlightPath.setMap (map)

two。 Remove polylin

To remove a Polyline from your map, call the setMap () method and pass null as its argument. In the following example, flightPath is a Polyline object:

`flightPath.setMap (null); `/ / This example adds a UI control allowing users to remove the polyline from the map. Var flightPath; var map; function initMap () {map = new google.maps.Map (document.getElementById ('map'), {zoom: 3, center: {lat: 0, lng:-180}, mapTypeId: google.maps.MapTypeId.TERRAIN}) Var flightPathCoordinates = [{lat: 37.772, lng:-122.214}, {lat: 21.291, lng:-157.821}, {lat:-18.142, lng: 178.431}, {lat:-27.467, lng: 153.027}] FlightPath = new google.maps.Polyline ({path: flightPathCoordinates, strokeColor:'# FF0000', strokeOpacity: 1.0, strokeWeight: 2}); addLine ();} function addLine () {flightPath.setMap (map);} function removeLine () {flightPath.setMap (null);}

3. Check polylin

The Polyline specifies a series of coordinates as an array of LatLng objects. These coordinates determine the path of the line. To retrieve these coordinates, call getPath (), which returns an array of type MVCArray. You can manipulate and check the array using the following operations:

GetAt () returns the LatLng at a given index value starting at zero

InsertAt () inserts the passed LatLng at a given index value starting at zero. Note that any existing coordinates at the index value will be moved forward

RemoveAt () removes the LatLng at a given index value starting at zero

Note: you cannot directly use the mvcArray [I] syntax to retrieve the I element of an array. You must use mvcArray.getAt (I).

/ / This example creates an interactive map which constructs a polyline based on / / user clicks. Note that the polyline only appears once its path property / / contains two LatLng coordinates. Var poly; var map; function initMap () {map = new google.maps.Map (document.getElementById ('map'), {zoom: 7, center: {lat: 41.879, lng:-87.624} / / Center the map on Chicago, USA. }); poly = new google.maps.Polyline ({strokeColor:'# 0000000, strokeOpacity: 1.0, strokeWeight: 3}); poly.setMap (map); / / Add a listener for the click event map.addListener ('click', addLatLng);} / / Handles click events on a map, and adds a new point to the Polyline. Function addLatLng (event) {var path = poly.getPath (); / / Because path is an MVCArray, we can simply append a new coordinate / / and it will automatically appear. Path.push (event.latLng); / / Add a new marker at the new plotted point on the polyline. Var marker = new google.maps.Marker ({position: event.latLng, title:'#'+ path.getLength (), map: map});}

4. Custom Polyline

You can add vector-based images in symbolic form to polylines. You can have full control over the appearance of polylines on your map by using a combination of symbols and PolylineOptions classes. See symbols for information about arrowheads, dashed lines, custom symbols, and animated symbols.

Polygon

A polygon represents an area enclosed by a closed path (or loop), defined by a series of coordinates. Polygon objects are similar to Polyline objects in that they both contain a series of ordered coordinates. Polygons are drawn with strokes and fills. You can define custom colors, weights, and opacity for polygon edges (strokes), and custom colors and opacity for enclosed areas (filled areas). Colors should be expressed in hexadecimal HTML format. Color names are not supported.

Polygon objects describe complex shapes, including:

Multiple discontinuous regions defined by a single polygon

Area with holes

The intersection of one or more regions.

1. Add multiple deformations

Because the polygon region may contain several different paths, the paths property of the Polygon object specifies an array of arrays, each of type MVCArray. Each array defines a different sequence of ordered LatLng coordinates.

For simple polygons that include only one path, you can use a single array of LatLng coordinates to build Polygon. When building, Google Maps JavaScript API will convert the simple array into an array of arrays when it is stored in the paths property. API provides a simple getPath () method for polygons that include a path.

Note: if you build a simple polygon in this way, you still need to retrieve the polygon's value by manipulating the path in the form of MVCArray.

The editable property of the polygon specifies whether you can edit the shape. See user editable shapes below. Similarly, you can also allow users to drag shapes by setting the draggable property.

/ / This example creates a simple polygon representing the Bermuda Triangle. Function initMap () {var map = new google.maps.Map (document.getElementById ('map'), {zoom: 5, center: {lat: 24.886, lng:-70.268}, mapTypeId: google.maps.MapTypeId.TERRAIN}); / / Define the LatLng coordinates for the polygon's path. Var triangleCoords = [{lat: 25.774, lng:-80.190}, {lat: 18.466, lng:-66.118}, {lat: 32.321, lng:-64.757}, {lat: 25.774, lng:-80.190}]; / / Construct the polygon. Var bermudaTriangle = new google.maps.Polygon ({paths: triangleCoords, strokeColor:'# FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor:'# FF0000', fillOpacity: 0.35}); bermudaTriangle.setMap (map);}

The Polygon in the example above contains four sets of LatLng coordinates, but note that the position defined by the * group coordinates is the same as that defined by the * * group coordinates, which is used to complete the loop. In practice, however, because polygons define closed areas, you do not need to specify a set of coordinates. Google Maps JavaScript API will automatically complete the polygon by drawing a stroke to connect one position of any given path back to * position.

two。 Remove polygon

To remove polygons from your map, call the setMap () method and pass null as its argument. In the following example, bermudaTriangle is a polygonal object:

BermudaTriangle.setMap (null)

3. Check polygons

Polygons specify their coordinate series as an array of arrays, where each array is of type MVCArray. Each "leaf" array is an array of LatLng coordinates that specify a single path. To retrieve these coordinates, call the getPaths () method of the Polygon object. Because the array is MVCArray, you need to manipulate and check the array using the following operations:

GetAt () returns the LatLng at a given index value starting at zero

InsertAt () inserts the passed LatLng at a given index value starting at zero. Note that any existing coordinates at the index value will be moved forward

RemoveAt () removes the LatLng at a given index value starting at zero

Rectangle

In addition to Polygon generic classes, Google Maps JavaScript API also provides classes that * Rectangle objects simplify their structure.

1. Add rectangle

Rectangle is similar to Polygon in that you can define custom colors, weights, and opacity for rectangular edges (strokes), as well as for areas within a rectangle (filled areas). Colors should be represented in hexadecimal numeric HTML style.

Unlike Polygon, you do not need to define a paths for Rectangle. Unlike polygons, a rectangle has a bounds property that defines its shape by specifying a google.maps.LatLngBounds for the rectangle.

The editable property of the rectangle specifies whether the user can edit the shape. See user editable shapes below. Similarly, you can also allow the user to drag the rectangle by setting the draggable property.

/ / This example adds a red rectangle to a map. Function initMap () {var map = new google.maps.Map (document.getElementById ('map'), {zoom: 11, center: {lat: 33.678, lng:-116.243}, mapTypeId: google.maps.MapTypeId.TERRAIN}) Var rectangle = new google.maps.Rectangle ({strokeColor:'# FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor:'# FF0000', fillOpacity: 0.35, map: map, bounds: {north: 33.685, south: 33.671, east:-116.234 West:-116.251}}) }

two。 Remove rectangle

To remove a rectangle from your map, call the setMap () method and pass null as its argument.

Rectangle.setMap (null)

Note that the above method does not delete the rectangle, but only removes it from the map. If you actually want to delete a rectangle, you should first remove it from the map, and then set the rectangle itself to null.

Circle

In addition to Polygon generic classes, Google Maps JavaScript API also provides classes that * Circle objects simplify their structure.

1. Add Circle

Circle is similar to Polygon in that you can define custom colors, weights, and opacity for the edges (strokes) of a circle, and for areas within a circle (filled areas). Colors should be represented in hexadecimal numeric HTML style.

Unlike Polygon, you do not need to define a paths for Circle. Circles have two additional shape definition properties:

Center specifies the google.maps.LatLng of the center of the circle

Radius specifies the radius of the circle (in meters)

The editable property of the circle specifies whether you can edit the shape. See user editable shapes below. Similarly, you can also allow users to drag circles by setting the draggable property.

/ / This example creates circles on the map, representing populations in North / / America. / / First, create an object containing LatLng and population for each city. Var citymap = {chicago: {center: {lat: 41.878, lng:-87.629}, population: 2714856}, newyork: {center: {lat: 40.714, lng:-74.005}, population: 8405837}, losangeles: {center: {lat: 34.052, lng:-118.243}, population: 3857799}, vancouver: {center: {lat:, lng:-123.1} Population: 603502}} Function initMap () {/ / Create the map. Var map = new google.maps.Map (document.getElementById ('map'), {zoom: 4, center: {lat: 37.090, lng:-95.712}, mapTypeId: google.maps.MapTypeId.TERRAIN}); / / Construct the circle for each value in citymap. / / Note: We scale the area of the circle based on the population. For (var city in citymap) {/ / Add the circle for this city to the map. Var cityCircle = new google.maps.Circle ({strokeColor:'# FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor:'# FF0000', fillOpacity: 0.35, map: map, center: citymap.center, radius: Math.sqrt (citymap.population) * 100});}

two。 Remove garden

To remove a circle from your map, call the setMap () method and pass null as its argument.

Circle.setMap (null)

Note that the above method does not delete the circle, but only removes the circle from the map. If you actually want to delete a circle, you should first remove it from the map, and then set the circle itself to null.

Shapes that can be edited and dragged by the user

Making the shape editable adds a handle to the shape, which you can use to reposition, reshape, and resize the shape directly on the map. You can also make the shape draggable so that the user can move it to another location on the map.

Changes made by the user to the object cannot be persisted across sessions. If you want to save the user's edits, you must collect and store the information yourself.

1. Make the shape editable

You can make any shape (Polyline, polygon, circle, and rectangle) editable by setting editable to true in the shape options.

two。 Set the shape to draggable

By default, the shape drawn on the map is fixed. To allow you to drag the shape to another location on the map, set draggable to true in the shape options.

3. Listen for editing events

When you edit a shape, an event is triggered when the editing is complete. These events are listed below.

Shape event circles radius_changed, center_changed polygon insert_at, remove_at, set_at, listeners must be set on the paths of polygons. If polygons have multiple paths, listener polylines insert_at, remove_at, set_at must be set on each path, and listener rectangle bounds_changed must be set on the path of polylines

Some related code snippets:

Google.maps.event.addListener (circle, 'radius_changed', function () {console.log (circle.getRadius ());}); google.maps.event.addListener (outerPath,' set_at', function () {console.log ('Vertex moved on outer path.');}); google.maps.event.addListener (innerPath,' insert_at', function () {console.log ('Vertex removed from inner path.');}) Google.maps.event.addListener (rectangle, 'bounds_changed', function () {console.log (' Bounds changed.');})

4. Listen for drag events

When you drag a shape, events are triggered at the beginning and end of the drag operation, and during the drag. For polylines, polygons, circles, and rectangles, the following events are triggered.

Events show that dragstart when the user starts to drag the shape to trigger drag during the user to drag the shape repeatedly triggered dragend when the user stops dragging the shape to trigger thank you for reading, the above is "how to use javascript to achieve map API add shape" of the content, after the study of this article, I believe that how to use javascript to achieve map API add shape has a deeper understanding of the problem, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report