Creating a dynamic polyline with custom data on Mapbox is a great way to enhance your mapping experience

Hey everyone, I'm looking to create a polyline or path on Mapbox using my own data. I came across an example on mapbox.com that shows how to draw a sine wave on the map. How can I customize this example to use my own data?

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Drawing and animating a line on a map</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.css' rel='stylesheet' />
<style>
  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>


<div id='map'></div>

<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiYmFhZ2lpIiwiYSI6ImNpZ295aTltdTAwZjl1c20xaTk0NjMxMHoifQ.qWMU19n430KrdzVcyky5bA';
var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([0, 0], 3);

// Adding a new line to the map with no points.
var polyline = L.polyline([]).addTo(map);

// Keeping track of points added to the map.
var pointsAdded = 0;

// Starting to draw the polyline.
add();

function add() {

    // `addLatLng` method adds a new latLng coordinate at the end of the
    // line. You can use your data or generate coordinates. Here
    // we are creating a sine wave using math.
    polyline.addLatLng(
        L.latLng(
            Math.cos(pointsAdded / 20) * 30,
            pointsAdded));

    // Moving the map along with the line being added.
    map.setView([0, pointsAdded], 3);

    // Calling `add()` function to continue drawing and panning the map
    // until all points have been added (360 in this case).
    if (++pointsAdded < 360) window.setTimeout(add, 100);
}
</script>


</body>
</html>

Answer №1

The example showcasing a sine wave may be regarded as overly intricate.

All that is required is the simple invocation of

polyline.addLatLng(L.latLng(lat,lng));

repeatedly. The values assigned to lat and lng will shape your polyline.

For instance:

// an approximate square near Versailles
polyline.addLatLng(L.latLng(48.831081,2.0770324));
polyline.addLatLng(L.latLng(48.8255436,2.125355));
polyline.addLatLng(L.latLng(48.7967555,2.1177344));
polyline.addLatLng(L.latLng(48.7948532,2.0553037));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encounter a snag while using Chrome to access an external API through jQuery

I am currently utilizing jQuery to make a request to an external API via AJAX. $.ajax({ url: https://exampleAPI, method: "GET", contentType: "text/plain", dataType: "jso ...

Personalized Pop-up Notification Upon Exiting Chrome Tab

I'm trying to implement a custom modal window that appears when the user attempts to close the Chrome Tab where my app is running by clicking the X button, displaying a message asking "Are you sure you want to close?". However, despite my efforts, I a ...

Utilize Laravel 8 and Vue Js to dynamically showcase retrieved data in input fields

I am facing a challenge with my Laravel 8 registration form using Vue js. Before submitting the form, I need to verify if the referring user exists in the database. If the user is found, I want to dynamically display their full name in an input field upon ...

ngMaterial flex layout not functioning properly

I can't seem to figure out why ngMaterial is not laying out my simple hello world app in a row. Despite checking the console for errors, I still can't see what I am doing wrong. I expected the content below to be displayed horizontally instead of ...

The feature 'forEach' is not available for the 'void' type

The following code is performing the following tasks: 1. Reading a folder, 2. Merging and auto-cropping images, and 3. Saving the final images into PNG files. const filenames = fs.readdirSync('./in').map(filename => { return path.parse(filen ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Using the if else and hasClass statements for validations in Cypress testing

I am struggling to validate the titles for a certain component. Here is my specific Cypress code snippet: it('Confirming the correctness of all tile titles', () => { cy.get('.bms-scoreboard__game-tile') .each(($el) => { ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

Removing a Dynamic Element in ReactJS

--CustomFieldSection.js-- import React, { Component } from 'react'; import CustomField from './CustomField.js'; class CustomFieldSection extends Component{ constructor(props){ super(props); this.stat ...

Tips for showcasing information entered into text fields within a single container within another container

After creating three divs, the first being a parent div and the next two being child divs placed side by side, I encountered an issue with displaying input values. Specifically, I wanted to take values from input text boxes within the second div (floatchil ...

Switch the background color of a list item according to a JSON search

Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

Dealing with a 404 Error in Node.js and Express Routing

After successfully creating a Node/Express app tutorial earlier, I encountered issues when trying to replicate it for a new project on both Ubuntu and Windows. The basic routing consistently fails and results in 404 errors, which is incredibly frustrating! ...

Avoiding the unnecessary re-rendering of input fields in React when their values change

I am developing a form that is dynamically generated using JSON data fetched from an API. The JSON structure includes information about the input elements to be rendered, such as name, type, placeholder, validation rules, and more. { name: { elemen ...

The custom directive in Vue utilizes the refreshed DOM element (also known as $el)

I am looking to create a custom directive that will replace all occurrences of 'cx' with <strong>cx</strong> in the Dom Tree. Here is my current approach: Vue.config.productionTip = false function removeKeywords(el, keyword){ i ...

Tips for implementing arraybuffer playback in video tags

I have been exploring ways to convert images from an HTML canvas into a video. After much research, I just want to be able to select a few images and turn them into a video. By passing multiple images to a library engine, I am able to receive an array buff ...

The function toJson() does not exist for the specified stdClass object

After following a tutorial on implementing websockets in Laravel to create a live commenting system, I encountered an error that I cannot figure out. Even though I followed the code exactly as demonstrated in the video, this error persists. Does anyone hav ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...