Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CodeFox's avatar

Display polyline in mapbox

Hey

So I've been experimenting with creating custom maps using the Google Maps API. I've been successful in creating static maps with an encoded polyline.

Unfortunately, Google Maps has a watermark in its static maps which I don't want. It seems that Mapbox doesn't have this watermark and so I'm trying to create a map with a polyline.

From looking at the API docs, it doesn't look like they support creating a map with a polyline and instead want co-ordinates. I've now got an array of data that looks like this:

-3.721921,
40.420988,
-3.721936,
40.421034,
-3.721953,
40.421078,
-3.721985,
40.421122,
-3.722021,
40.421148,

MapBox wants the data in this format:

    [38.893596444352134, -77.0381498336792],
    [38.89337933372204, -77.03792452812195],
    [38.89316222242831, -77.03761339187622],
    [38.893028615148424, -77.03731298446655],
    [38.892920059048464, -77.03691601753235],
    [38.892903358095296, -77.03637957572937],
    [38.89301191422077, -77.03592896461487],
    [38.89316222242831, -77.03549981117249],
    [38.89340438498248, -77.03514575958252],
    [38.893596444352134, -77.0349633693695]

Is there a way of converting the data I've put above into an acceptable format? I don't have any array keys etc to play with.

Alternatively, if someone knows how to create a Mapbox map with a polyline then that would be very helpful!

Thanks!

0 likes
2 replies
Connor-S-Parks's avatar
Level 8

This just seems like basic data manipulation... Something like this will suffice:

$values = [-3.721921, 40.420988, -3.721936, 40.421034, -3.721953, 40.421078, -3.721985, 40.421122, -3.722021, 40.421148];

function map(array $values = []) {
    $count = count($values);
    $map = [];
    for ($i = 0; $i < $count - $count % 2; $i += 2) {
        $map[] = [$values[$i], $values[$i + 1]];
    }

    return $map;
}

assert(map($values) === [
    [-3.721921, 40.420988],
    [-3.721936, 40.421034],
    [-3.721953, 40.421078],
    [-3.721985, 40.421122],
    [-3.722021, 40.421148],
]);
1 like

Please or to participate in this conversation.