Skip to content

Instantly share code, notes, and snippets.

@jsanz
Last active March 31, 2017 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanz/9d72a1a91039e7be0d49db1524cadedb to your computer and use it in GitHub Desktop.
Save jsanz/9d72a1a91039e7be0d49db1524cadedb to your computer and use it in GitHub Desktop.
Javascript: Center a CARTO BUILDER embed

Text by Álvaro Arredondo

You can do it in the URL, but it's a little bit tricky. When you move the view in an embed, you'll see the URL changes. The thing is, that URL is encoded, but is actually showing a bounding box (NE and SW coordinates). This is the structure:

https://{{map_url}}/embed?state={"map":{"ne":[x, y],"sw":[x, y]}}

Let's take your URL:

https://solutions.carto.com/builder/6b8d6968-cc26-11e6-b997-0ee66e2c9693/embed?

Now we'll add the bounding box part, for example, for coodinates 0,0 NE and 100,100 SW:

https://solutions.carto.com/builder/6b8d6968-cc26-11e6-b997-0ee66e2c9693/embed?state={"map":{"ne":[0, 0],"sw":[100, 100]}}

And now we'll have to encode that, but only the bit after "state=". We can use this simple online encoder/decoder:

Decoded: {"map":{"ne":[0, 0],"sw":[100, 100]}}
Encoded: %7B%22map%22%3A%7B%22ne%22%3A%5B0%2C%200%5D%2C%22sw%22%3A%5B100%2C%20100%5D%7D%7D

Finally, we'll have to change those %22 for the proper symbol, " which the URL is able to parse:

%7B"map"%3A%7B"ne"%3A%5B0%2C%200%5D%2C"sw"%3A%5B100%2C%20100%5D%7D%7D

Now let's add that all together!

https://solutions.carto.com/builder/6b8d6968-cc26-11e6-b997-0ee66e2c9693/embed?state=%7B"map"%3A%7B"ne"%3A%5B0%2C%200%5D%2C"sw"%3A%5B100%2C%20100%5D%7D%7D

So, taking this into account, what you have to do is:

  1. Figure out the bounding box coordinates (in lat/long) of the area you want the user to visualize when the map is opened. You can use this handy tool http://bboxfinder.com
  2. Place those coordinates instead of the red numbers in the URL, following the previous process.

IMPORTANT NOTE: the way BUILDER embed saves the state is not a documented feature and it can change anytime so this trick my not work and you need to check from time to time if the JSON object has changed.

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