Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
React Leaflet, how to draw polylines programmatically?

I want to draw lines between new clicked point and previous clicked point on Leaflet map everytime when i click on the map. I tried to do this with the code below:

import React, { useEffect, useState } from 'react';
import { Popup, Polyline, useMap} from 'react-leaflet';
import L from 'leaflet';

let oldPoint;


const DrawLines=()=> {

  const [isChecked,setIsChecked]=useState()
  const handleChange=(e)=> {
      setIsChecked(e.target.checked);
    console.log(isChecked)
    
  }

  useEffect(() => {
     console.log(isChecked)
  }, [isChecked])

  const map = useMap();

  let points;

  useEffect(() => {
    if (!map) return;
    const info = L.DomUtil.create('div', 'legend');

    const positon = L.Control.extend({
      options: {
        position: 'bottomleft'
      },

      onAdd: function () {
        info.textContent = 'Click on map';
        return info;
      }
    })

    map.on('click', (e) => {
      info.textContent = e.latlng;

      if(oldPoint != null){
        points=[[oldPoint.lat, oldPoint.lng],
        [e.latlng.lat, e.latlng.lng]];
        console.log(points);
      }
      oldPoint = e.latlng;

    })

    map.addControl(new positon());

  }, [map])
  
  

  return (
    <>
      {points!=null&&(isChecked===undefined||isChecked===false)&&<Polyline positions={points} weight={10} opacity={0.7} pathOptions={{ color: "red" }} >
       <Popup>
        <div>
         <label>
           Done
          <input type="checkbox"
          onClick={(e) => {handleChange(e)}}/>            
         </label>
          </div>
        </Popup> </Polyline>}
       {points!=null&&isChecked===true&& <Polyline  positions={[points]} weight={10} opacity={0.7} pathOptions={{ color: "green" }} >  <Popup>
        <div>
         <label>
         Done
          <input type="checkbox" defaultChecked={true}
          onClick={(e) => {handleChange(e)}}/>            
         </label>
          </div>
        </Popup></Polyline>}
          </>
      )
}

This code draws polylines when points are given manually. I am able to get coordinates when i click on Leaflet map. But the code does not draw lines between these two clicked points in jsx script programmatically.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!