Mapbox draw polygon

Mapbox draw polygon DEFAULT

API Reference

To use Draw

// Create a Mapbox GL JS mapvarmap=newMap(mapOptions);// Create a Draw controlvardraw=newMapboxDraw(drawOptions);// Add the Draw control to your mapmap.addControl(draw);

Draw only works after the Mapbox GL JS map has loaded, so you must interact with Draw only after your map's event:

map.on('load',function(){draw.add({..});});

Options

All of the following options are optional.

  • , boolean (default ): Whether or not to enable keyboard interactions for drawing.
  • , boolean (default ): Whether or not to enable touch interactions for drawing.
  • , boolean (default ): Whether or not to enable box selection of features with ++drag. If , ++drag zooms into an area.
  • , number (default: ): Number of pixels around any feature or vertex (in every direction) that will respond to a click.
  • , number (default: ): Number of pixels around any feature of vertex (in every direction) that will respond to a touch.
  • , Object: Hide or show individual controls. Each property's name is a control, and value is a boolean indicating whether the control is on or off. Available control names are , , , , and . By default, all controls are on. To change that default, use .
  • , boolean (default: ): The default value for . For example, if you would like all controls to be off by default, and specify an allowed list with , use .
  • , Array<Object>: An array of map style objects. By default, Draw provides a map style for you. To learn about overriding styles, see the Styling Draw section below.
  • , Object: over ride the default modes with your own. can be used to see the default values. More information on custom modes can be found here.
  • , String (default: ): the mode (from ) that user will first land in.
  • , boolean (default: ): properties of a feature will also be available for styling and prefixed with , e.g.,

Modes

By default MapboxDraw ships with a few modes. These modes aim to cover the basic needed functionally for MapboxDraw to create the core GeoJSON feature types. Along with these, MapboxDraw also supports custom modes. Click here for more details.

The mode name strings are available as an enum at .

Lets you select, delete, and drag features.

In this mode, features can have their selected state changed by the user.

Draw is in mode by default, and will automatically transition into mode again every time the user finishes drawing a feature or exits mode.

Lets you select, delete, and drag vertices; and drag features.

mode does not apply to point features, because they have no vertices.

Draw enters mode when the user clicks a vertex of a selected line or polygon. So mode typically follows mode.

Lets you draw a LineString feature.

Lets you draw a Polygon feature.

Lets you draw a Point feature.

API Methods

returns an instance of Draw with the following API:

This method takes either a GeoJSON Feature, FeatureCollection, or Geometry and adds it to Draw. It returns an array of ids for interacting with the added features. If a feature does not have its own id, one is automatically generated.

The supported GeoJSON feature types are supported: , , , , , and .

If you a feature with an id that is already in use, the existing feature will be updated and no new feature will be added.

Example without a specified feature id:

varfeature={type: 'Point',coordinates: [0,0]};varfeatureIds=draw.add(feature);console.log(featureIds);//=> ['some-random-string']

Example with a specified feature id:

varfeature={id: 'unique-id',type: 'Feature',properties: {},geometry: {type: 'Point',coordinates: [0,0]}};varfeatureIds=draw.add(feature);console.log(featureIds)//=> ['unique-id']

Returns the GeoJSON feature in Draw with the specified id, or if the id matches no feature.

Example:

varfeatureIds=draw.add({type: 'Point',coordinates: [0,0]});varpointId=featureIds[0];console.log(draw.get(pointId));//=> { type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0] } }

Returns an array of feature ids for features currently rendered at the specified point.

Notice that the argument requires , coordinates from pixel space, rather than longitude, latitude coordinates.

With this function, you can use the coordinates provided by mouse events to get information out of Draw.

varfeatureIds=Draw.getFeatureIdsAt({x: 20,y: 20});console.log(featureIds)//=> ['top-feature-at-20-20', 'another-feature-at-20-20']

Returns an array of feature ids for features currently selected.


Returns a FeatureCollection of all the features currently selected.


Returns a FeatureCollection of Points representing all the vertices currently selected.


Returns a FeatureCollection of all features.

Example:

draw.add({type: 'Point',coordinates: [0,0]});draw.add({type: 'Point',coordinates: [1,1]});draw.add({type: 'Point',coordinates: [2,2]});console.log(draw.getAll());// {// type: 'FeatureCollection',// features: [// {// id: 'random-0'// type: 'Feature',// geometry: {// type: 'Point',// coordinates: [0, 0]// }// },// {// id: 'random-1'// type: 'Feature',// geometry: {// type: 'Point',// coordinates: [1, 1]// }// },// {// id: 'random-2'// type: 'Feature',// geometry: {// type: 'Point',// coordinates: [2, 2]// }// }// ]// }

Removes features with the specified ids. Returns the draw instance for chaining.

In mode, deleting the active feature will exit that mode and revert to the mode.

Example:

varfeature={type: 'Point',coordinates: [0,0]};varids=draw.add(feature);draw.delete(ids).getAll();// { type: 'FeatureCollection', features: [] }

Removes all features. Returns the draw instance for chaining.

Example:

draw.add({type: 'Point',coordinates: [0,0]});draw.deleteAll().getAll();// { type: 'FeatureCollection', features: [] }

Sets Draw's features to those in the specified FeatureCollection.

Performs whatever delete, create, and update actions are necessary to make Draw's features match the specified FeatureCollection. Effectively, this is the same as followed by except that it does not affect performance as much.

Example:

varids=draw.set({type: 'FeatureCollection',features: [{type: 'Feature',properties: {},id: 'example-id',geometry: {type: 'Point',coordinates: [0,0]}}]});// ['example-id']

Invokes the current mode's action. Returns the draw instance for chaining.

In mode, this deletes all selected features.

In mode, this deletes the selected vertices.

In drawing modes, this cancels drawing and reverts Draw to mode.

If you want to delete features regardless of the current mode, use the or function.


Invokes the current mode's action. Returns the draw instance for chaining.

In mode, this combines all selected features into a single Multi* feature, as long as they are all of the same geometry type. For example:

  • Selection is two LineStrings => MultiLineString
  • Selection is a MultiLineString and a LineString => MultiLineString
  • Selection is two MultiLineStrings => MultiLineString

Calling this function when features of different geometry types are selected will not cause any changes. For example:

  • Selection is a Point and a LineString => no action taken
  • Selection is a MultiLineString and a MultiPoint => no action taken

In mode and drawing modes, no action is taken.


Invokes the current mode's action. Returns the draw instance for chaining.

In mode, this splits each selected Multi* feature into its component feature parts, and leaves non-multifeatures untouched. For example:

  • Selection is MultiLineString of two parts => LineString, LineString
  • Selection is MultiLineString of three parts => LineString, LineString, LineString
  • Selection is MultiLineString of two parts and one Point => LineString, LineString, Point
  • Selection is LineString => LineString

In the and drawing modes, no action is taken.


Returns Draw's current mode. For more about the modes, see above.


Changes Draw to another mode. Returns the draw instance for chaining.

The argument must be one of the mode names described above and enumerated in .

, , and modes accept an object.

// `simple_select` options{// Array of ids of features that will be initially selectedfeatureIds: Array<string>}
// `direct_select` options{// The id of the feature that will be directly selected (required)featureId: string}
// `draw_line_string` options{// The id of the LineString to continue drawingfeatureId: string,// The point to continue drawing fromfrom: Feature<Point>|Point|Array<number>}

Sets the value of a property on the feature with the specified id. Returns the draw instance for chaining.

This is helpful if you are using Draw's features as your primary data store in your application.

Events

Draw fires a number of events. All of these events are namespaced with and are emitted from the Mapbox GL JS map object. All events are all triggered by user interaction.

map.on('draw.create',function(e){console.log(e.features);});

If you programmatically invoke a function in the Draw API, any event that directly corresponds with that function will not be fired. For example, if you invoke , there will be no corresponding event, since you already know what you've done. Subsequent events may fire, though, that do not directly correspond to the invoked function. For example, if you have a one feature selected and then invoke , you will not see a event (because that directly corresponds with the invoked function) but you will see a event, since by changing the mode you indirectly deselected a feature.

Fired when a feature is created. The following interactions will trigger this event:

  • Finish drawing a feature. Simply clicking will create a Point. A LineString or Polygon is only created when the user has finished drawing it — i.e. double-clicked the last vertex or hit Enter — and the drawn feature is valid.

The event data is an object with the following shape:

{// Array of GeoJSON objects representing the features that were createdfeatures: Array<Object>}

Fired when one or more features are deleted. The following interactions will trigger this event:

  • Click the trash button when one or more features are selected in mode.
  • Hit the or keys when one or features are selected in mode.
  • Invoke when you have a feature selected in mode.

The event data is an object with the following shape:

{// Array of GeoJSON objects representing the features that were deletedfeatures: Array<Feature>}

Fired when features are combined. The following interactions will trigger this event:

  • Click the Combine button when more than one features are selected in mode.
  • Invoke when more than one features are selected in mode.

The event data is an object with the following shape:

{deletedFeatures: Array<Feature>,// Array of deleted features (those incorporated into new multifeatures)createdFeatures: Array<Feature>// Array of created multifeatures}

Fired when features are uncombined. The following interactions will trigger this event:

  • Click the Uncombine button when one or more multifeatures are selected in mode. Non-multifeatures may also be selected.
  • Invoke when one or more multifeatures are selected in mode. Non-multifeatures may also be selected.

The event data is an object with the following shape:

{deletedFeatures: Array<Object>,// Array of deleted multifeatures (split into features)createdFeatures: Array<Object>// Array of created features}

Fired when one or more features are updated. The following interactions will trigger this event, which can be subcategorized by :

    • Finish moving one or more selected features in mode. The event will only fire when the movement is finished (i.e. when the user releases the mouse button or hits ).
    • Finish moving one or more vertices of a selected feature in mode. The event will only fire when the movement is finished (i.e. when the user releases the mouse button or hits , or her mouse leaves the map container).
    • Delete one or more vertices of a selected feature in mode, which can be done by hitting the or keys, clicking the Trash button, or invoking .
    • Add a vertex to the selected feature by clicking a midpoint on that feature in mode.

This event will not fire when a feature is created or deleted. To track those interactions, listen for and events.

The event data is an object with the following shape:

{ features: Array<Feature>,// Array of features that were updatedaction: string// Name of the action that triggered the update}

Fired when the selection is changed (i.e. one or more features are selected or deselected). The following interactions will trigger this event:

  • Click on a feature to select it.
  • When a feature is already selected, shift-click on another feature to add it to the selection.
  • Click on a vertex to select it.
  • When a vertex is already selected, shift-click on another vertex to add it to the selection.
  • Create a box-selection that includes at least one feature.
  • Click outside the selected feature(s) to deselect.
  • Click away from the selected vertex(s) to deselect.
  • Finish drawing a feature (features are selected just after they are created).
  • When a feature is already selected, invoke such that the feature becomes deselected.
  • Use to switch to mode and immediately select the specified features.
  • Use , or to delete feature(s).

The event data is an object with the following shape:

{features: Array<Feature>// Array of features that are selected after the change}

Fired when the mode is changed. The following interactions will trigger this event:

  • Click the point, line, or polygon buttons to begin drawing (enter a mode).
  • Finish drawing a feature (enter mode).
  • While in mode, click on an already selected feature (enter mode).
  • While in mode, click outside all features (enter mode).

This event is fired just after the current mode stops and just before the next mode starts. A render will not happen until after all event handlers have been triggered, so you can force a mode redirect by calling inside a handler.

The event data is an object with the following shape:

{mode: string// The next mode, i.e. the mode that Draw is changing to}

and modes can be initiated with options specific to that mode (see above).

Fired just after Draw calls on the Mapbox GL JS map. This does not imply that the set data call has finished updating the map, just that the map is being updated.

Fired as the state of Draw changes to enable and disable different actions. Following this event will enable you know if , and will have an effect.

{ actions: { trash: true combineFeatures: false,uncombineFeatures: false}}

Styling Draw

Draw uses a map style that adheres to the Mapbox GL Style Spec with a few caveats.

source

The GL Style Spec requires each layer to have a source. However, do not provide a when styling Draw.

Draw moves features between sources in order to fine-tune performance. Because of this, Draw will provide a for you automatically.

The s that Draw provides are named and .

id

The GL Style Spec also requires an id. You must provide an id. Draw will then add the suffixes and to your id.

In your custom style, you will want to use the following feature properties:

propertyvaluesfunction
metafeature, midpoint, vertex and are used on points added to the map to communicate polygon and line handles. is used for all features.
activetrue, falseA feature is active when it is 'selected' in the current mode. and are strings.
modesimple_select, direct_select, draw_point, draw_line_string, draw_polygonIndicates which mode Draw is currently in.

Draw also provides a few more properties on features, but they should not be used for styling. For details on them, see "Using Draw with Mapbox GL JS's " below.

If is set to the properties of a feature will also be available for styling. All user properties are prefixed with to make sure they do not clash with the Draw properties.

Example Custom Styles

See EXAMPLES.md for examples of custom styles.

Using Draw with Mapbox GL JS's

propertyvaluesfunction
idstringonly available when is
parentstringonly available when is not
coord_pathstringa separated path to one [lon, lat] entity in the parents coordinates
lonnumberthe longitude value of a handle. Only available when is .
latnumberthe latitude value of a handle. Only available when is .
Sours: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md

Draw a polygon

packagecom.mapbox.mapboxandroiddemo.examples.dds;

importandroid.graphics.Color;

importandroid.os.Bundle;

importandroidx.annotation.NonNull;

importandroidx.appcompat.app.AppCompatActivity;

importcom.mapbox.geojson.Point;

importcom.mapbox.geojson.Polygon;

importcom.mapbox.mapboxandroiddemo.R;

importcom.mapbox.mapboxsdk.Mapbox;

importcom.mapbox.mapboxsdk.maps.MapView;

importcom.mapbox.mapboxsdk.maps.MapboxMap;

importcom.mapbox.mapboxsdk.maps.OnMapReadyCallback;

importcom.mapbox.mapboxsdk.maps.Style;

importcom.mapbox.mapboxsdk.style.layers.FillLayer;

importcom.mapbox.mapboxsdk.style.sources.GeoJsonSource;

importjava.util.ArrayList;

importjava.util.List;

importstaticcom.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor;

* Draw a vector polygon on a map with the Mapbox Android SDK.

*/

publicclassDrawPolygonActivityextendsAppCompatActivity{

privateMapView mapView;

privatestaticfinalList<List<Point>> POINTS =newArrayList<>();

privatestaticfinalList<Point> OUTER_POINTS =newArrayList<>();

static{

OUTER_POINTS.add(Point.fromLngLat(-122.685699,45.522585));

OUTER_POINTS.add(Point.fromLngLat(-122.708873,45.534611));

OUTER_POINTS.add(Point.fromLngLat(-122.678833,45.530883));

OUTER_POINTS.add(Point.fromLngLat(-122.667503,45.547115));

OUTER_POINTS.add(Point.fromLngLat(-122.660121,45.530643));

OUTER_POINTS.add(Point.fromLngLat(-122.636260,45.533529));

OUTER_POINTS.add(Point.fromLngLat(-122.659091,45.521743));

OUTER_POINTS.add(Point.fromLngLat(-122.648792,45.510677));

OUTER_POINTS.add(Point.fromLngLat(-122.664070,45.515008));

OUTER_POINTS.add(Point.fromLngLat(-122.669048,45.502496));

OUTER_POINTS.add(Point.fromLngLat(-122.678489,45.515369));

OUTER_POINTS.add(Point.fromLngLat(-122.702007,45.506346));

OUTER_POINTS.add(Point.fromLngLat(-122.685699,45.522585));

POINTS.add(OUTER_POINTS);

}

@Override

protectedvoidonCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

Mapbox.getInstance(this,getString(R.string.access_token));

setContentView(R.layout.activity_dds_draw_polygon);

mapView =findViewById(R.id.mapView);

mapView.onCreate(savedInstanceState);

mapView.getMapAsync(newOnMapReadyCallback(){

@Override

publicvoidonMapReady(@NonNullfinalMapboxMap mapboxMap){

mapboxMap.setStyle(Style.MAPBOX_STREETS,newStyle.OnStyleLoaded(){

@Override

publicvoidonStyleLoaded(@NonNullStyle style){

style.addSource(newGeoJsonSource("source-id",Polygon.fromLngLats(POINTS)));

style.addLayerBelow(newFillLayer("layer-id","source-id").withProperties(

fillColor(Color.parseColor("#3bb2d0"))),"settlement-label"

);

}

});

}

});

}

@Override

publicvoidonResume(){

super.onResume();

mapView.onResume();

}

@Override

protectedvoidonStart(){

super.onStart();

mapView.onStart();

}

@Override

protectedvoidonStop(){

super.onStop();

mapView.onStop();

}

@Override

publicvoidonPause(){

super.onPause();

mapView.onPause();

}

@Override

publicvoidonSaveInstanceState(Bundle outState){

super.onSaveInstanceState(outState);

mapView.onSaveInstanceState(outState);

}

@Override

publicvoidonLowMemory(){

super.onLowMemory();

mapView.onLowMemory();

}

@Override

protectedvoidonDestroy(){

super.onDestroy();

mapView.onDestroy();

}

}

Sours: https://docs.mapbox.com/android/maps/examples/draw-a-polygon/
  1. Ibm drivers download
  2. Ford transit toy
  3. Dogs cuddling gif
  4. Canal de pasiones

npm

importmapboxGlfrom'mapbox-gl';
importMapboxDrawfrom'@mapbox/mapbox-gl-draw';
importSplitPolygonModefrom'mapbox-gl-draw-split-polygon-mode';
importmapboxGlDrawPassingModefrom'mapbox-gl-draw-passing-mode';
constmap=newmapboxgl.Map({
  container:'map',// container id
  style:'mapbox://styles/mapbox/streets-v11',
  center:[-91.874,42.76],// starting position
  zoom:12,// starting zoom
constdraw=newMapboxDraw({
  displayControlsDefault:false,
  modes:Object.assign(MapboxDraw.modes,{
    splitPolygonMode: SplitPolygonMode,
    passing_mode_line_string:mapboxGlDrawPassingMode(
MapboxDraw.modes.draw_line_string
// when mode drawing should be activated
draw.changeMode('splitPolygonMode');

Example

Acknowledgement

The main function responsible for cutting the features is from: https://gis.stackexchange.com/a/344277/145409

License

MIT © ReyhaneMasumi

Sours: https://www.npmjs.com/package/mapbox-gl-draw-split-polygon-mode
Building Mapbox Visualizations

Show drawn polygon area

<!DOCTYPEhtml>

<html>

<head>

<metacharset="utf-8"/>

<title>Show drawn polygon area</title>

<metaname="viewport"content="initial-scale=1,maximum-scale=1,user-scalable=no"/>

<scriptsrc="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>

<linkhref="https://unpkg.com/[email protected]/dist/maplibre-gl.css"rel="stylesheet"/>

<style>

body{margin: 0;padding: 0;}

#map{position: absolute;top: 0;bottom: 0;width: 100%;}

</style>

</head>

<body>

<style>

.calculation-box{

height: 75px;

width: 150px;

position: absolute;

bottom: 40px;

left: 10px;

background-color:rgba(255, 255, 255, 0.9);

padding: 15px;

text-align: center;

}

p{

font-family:'Open Sans';

margin: 0;

font-size: 13px;

}

</style>

<scriptsrc="https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v3.0.11/turf.min.js"></script>

<scriptsrc="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.js"></script>

<link

rel="stylesheet"

href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.css"

type="text/css"

/>

<divid="map"></div>

<divclass="calculation-box">

<p>Draw a polygon using the draw tools.</p>

<divid="calculated-area"></div>

</div>

<script>

var map =newmaplibregl.Map({

container:'map',

style:

'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',

center:[-91.874,42.76],

zoom:12

});

var draw =newMapboxDraw({

displayControlsDefault:false,

controls:{

polygon:true,

trash:true

}

});

map.addControl(draw);

map.on('draw.create', updateArea);

map.on('draw.delete', updateArea);

map.on('draw.update', updateArea);

functionupdateArea(e){

var data = draw.getAll();

var answer = document.getElementById('calculated-area');

if(data.features.length >0){

var area = turf.area(data);

var rounded_area = Math.round(area *100)/100;

answer.innerHTML =

'<p><strong>'+

rounded_area +

'</strong></p><p>square meters</p>';

}else{

answer.innerHTML ='';

if(e.type !=='draw.delete')

alert('Use the draw tools to draw a polygon!');

}

}

</script>

</body>

</html>

Sours: https://maplibre.org/maplibre-gl-js-docs/example/mapbox-gl-draw/

Polygon mapbox draw

Draw a polygon and calculate its area

<!DOCTYPEhtml>

<html>

<head>

<metacharset="utf-8">

<title>Draw a polygon and calculate its area</title>

<metaname="viewport"content="initial-scale=1,maximum-scale=1,user-scalable=no">

<linkhref="https://api.mapbox.com/mapbox-gl-js/v2.5.1/mapbox-gl.css"rel="stylesheet">

<scriptsrc="https://api.mapbox.com/mapbox-gl-js/v2.5.1/mapbox-gl.js"></script>

<style>

body{margin: 0;padding: 0;}

#map{position: absolute;top: 0;bottom: 0;width: 100%;}

</style>

</head>

<body>

<style>

.calculation-box{

height: 75px;

width: 150px;

position: absolute;

bottom: 40px;

left: 10px;

background-color:rgba(255, 255, 255, 0.9);

padding: 15px;

text-align: center;

}

p{

font-family:'Open Sans';

margin: 0;

font-size: 13px;

}

</style>

<scriptsrc="https://unpkg.com/@turf/[email protected]/turf.min.js"></script>

<scriptsrc="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.2/mapbox-gl-draw.js"></script>

<linkrel="stylesheet"href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.2/mapbox-gl-draw.css"type="text/css">

<divid="map"></div>

<divclass="calculation-box">

<p>Click the map to draw a polygon.</p>

<divid="calculated-area"></div>

</div>

<script>

mapboxgl.accessToken ='<your access token here>';

const map =newmapboxgl.Map({

container:'map',

style:'mapbox://styles/mapbox/satellite-v9',

center:[-91.874,42.76],

zoom:12

});

const draw =newMapboxDraw({

displayControlsDefault:false,

controls:{

polygon:true,

trash:true

},

defaultMode:'draw_polygon'

});

map.addControl(draw);

map.on('draw.create', updateArea);

map.on('draw.delete', updateArea);

map.on('draw.update', updateArea);

functionupdateArea(e){

const data = draw.getAll();

const answer = document.getElementById('calculated-area');

if(data.features.length >0){

const area = turf.area(data);

const rounded_area = Math.round(area *100)/100;

answer.innerHTML =`<p><strong>${rounded_area}</strong></p><p>square meters</p>`;

}else{

answer.innerHTML ='';

if(e.type !=='draw.delete')

alert('Click the map to draw a polygon.');

}

}

</script>

</body>

</html>

Sours: https://docs.mapbox.com/mapbox-gl-js/example/mapbox-gl-draw/
4.5 Fill/Polygon Styling - Interactive Maps with Mapbox

She was silent. I asked, - How will we continue to live. Continues to be silent. is about to cry.

Similar news:

It hurt, I stood stupidly until Katya began to beat me on the back and shoulders with a whip, demanding that. I wave passionately. I waved, then Gopher raised a not clean dick to my face and said: "Now, let me finish.



1228 1229 1230 1231 1232