Skip to content

Instantly share code, notes, and snippets.

@michiel
Last active March 7, 2023 16:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save michiel/7984227 to your computer and use it in GitHub Desktop.
Save michiel/7984227 to your computer and use it in GitHub Desktop.
Add jitter to latitude/longitude
//
// Make a few assumptions and add noise to latitude/longitude position
// Ex, console.log(jitter(-26.4853429150483, -49.072945734375, 5));
//
var rad_Earth = 6378.16;
var one_degree = (2 * Math.PI * rad_Earth) / 360;
var one_km = 1 / one_degree;
function randomInRange(from, to, fixed) {
fixed = fixed || 10;
return (Math.random() * (to - from) + from).toFixed(fixed) * 1;
}
function jitter(lat, lng, kms, fixed) {
return {
lat : randomInRange(
lat - (kms * one_km),
lat + (kms * one_km),
fixed
),
lng : randomInRange(
lng - (kms * one_km),
lng + (kms * one_km),
fixed
)
};
}
@balasmeh
Copy link

balasmeh commented Jan 2, 2020

could you please add some description of your method sir?, and how can rut it using google map

@butschster
Copy link

butschster commented Aug 17, 2020

Thx for an example!

<?php

use MStaack\LaravelPostgis\Geometries\Point;

/**
 * Данный класс добавляет шум в координаты
 */
class Jitter
{
    const ONE_KM = 0.008983120447446;

    private float $variation;
    private Point $point;
    private int $precision;

    /**
     * @param Point $point Координата
     * @param int $meters Возможное отклонение координат относительно стартовой позиции в метрах
     * @param int $precision Точность исходящей координаты (кол-во знаков после запятой)
     */
    public function __construct(Point $point, int $meters = 10, int $precision = 10)
    {
        $this->variation = $meters / 1000 * static::ONE_KM;

        $this->point = $point;
        $this->precision = $precision;
    }

    /**
     * Создание новой точки с рандомным отклонением
     *
     * @return Point
     */
    public function make(): Point
    {
        return new Point(
            $this->randomize($this->point->getLat()),
            $this->randomize($this->point->getLng())
        );
    }

    protected function randomize(float $coordinate): float
    {
        $from = $coordinate - $this->variation;
        $to = $coordinate + $this->variation;

        return round(
            (mt_rand() / (mt_getrandmax() + 1)) * ($to - $from) + $from,
            $this->precision
        );
    }
}

@lbrutti
Copy link

lbrutti commented Feb 10, 2021

Thank you! used as is in a mapbox map and worked as charm
🍻

@emiliobasualdo
Copy link

Great!
For the sake of Typescript

Instead of
return (Math.random() * (to - from) + from).toFixed(fixed) * 1;
maybe
return parseFloat((Math.random() * (to - from) + from).toFixed(fixed));
?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment