Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7277987
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T22:48:51+00:00 2026-05-28T22:48:51+00:00

I need to convert map coordinates into pixels (in order to make a clickable

  • 0

I need to convert map coordinates into pixels (in order to make a clickable map in html).

Here is a sample map (made using the Basemap package from matplotlib). I have put some labels on it and attempted to calculate the midpoints of the labels in pixels:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

## Step 0: some points to plot
names = [u"Reykjavík", u"Höfn", u"Húsavík"]
lats = [64.133333, 64.25, 66.05]
lons = [-21.933333, -15.216667, -17.316667]

## Step 1: draw a map using matplotlib/Basemap
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

M = Basemap(projection='merc',resolution='c',
            llcrnrlat=63,urcrnrlat=67,
            llcrnrlon=-24,urcrnrlon=-13)

x, y = M(lons, lats) # transform coordinates according to projection
boxes = []
for xa, ya, name in zip(x, y, names):
    box = plt.text(xa, ya, name,
        bbox=dict(facecolor='white', alpha=0.5))
    boxes.append(box)

M.bluemarble() # a bit fuzzy at this resolution...
plt.savefig('test.png', bbox_inches="tight", pad_inches=0.01)

# Step 2: get the coordinates of the textboxes in pixels and calculate the
# midpoints
F = plt.gcf() # get current figure
R = F.canvas.get_renderer()
midpoints = []
for box in boxes:
    bb = box.get_window_extent(renderer=R)
    midpoints.append((int((bb.p0[0] + bb.p1[0]) / 2),
            int((bb.p0[1] + bb.p1[1]) / 2)))

These calculated points are in the approximately correct relative relation to each other, but do not coincide with the true points. The following code snippet should put a red dot on the midpoint of each label:

# Step 3: use PIL to draw dots on top of the labels
from PIL import Image, ImageDraw

im = Image.open("test.png")
draw = ImageDraw.Draw(im)
for x, y in midpoints:
    y = im.size[1] - y # PIL counts rows from top not bottom
    draw.ellipse((x-5, y-5, x+5, y+5), fill="#ff0000")
im.save("test.png", "PNG")

sample output

  • Red dots should be in the middle of the labels.

I guess that the error comes in where I extract the coordinates of the text boxes (in Step #2). Any help much appreciated.

Notes

  • Perhaps the solution is something along the lines of this answer?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T22:48:52+00:00Added an answer on May 28, 2026 at 10:48 pm

    Two things are happening to cause your pixel positions to be off.

    1. The dpi used to calculated the text position is different from that used to save the figure.

    2. When you use the bbox_inches option in the savefig call, it eliminates a lot of white space. You don’t take this into account when you are drawing your circles with PIL (or checking where someone clicked. Also you add a padding in this savefig call that you may need to account for if it’s very large (as I show in my example below). Probably it will not matter if you still use 0.01.

    To fix this first issue, just force the figure and the savefig call to use the same DPI.

    To fix the second issue, document the (0,0) position (Axes units) of the axes in pixels, and shift your text positions accordingly.

    Here’s a slightly modified version of your code:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    ## Step 0: some points to plot
    names = [u"Reykjavík", u"Höfn", u"Húsavík"]
    lats = [64.133333, 64.25, 66.05]
    lons = [-21.933333, -15.216667, -17.316667]
    
    ## Step 1: draw a map using matplotlib/Basemap
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    
    # predefined dpi
    FIGDPI=80
    
    # set dpi of figure, so that all calculations use this value
    plt.gcf().set_dpi(FIGDPI)
    
    M = Basemap(projection='merc',resolution='c',
                llcrnrlat=63,urcrnrlat=67,
                llcrnrlon=-24,urcrnrlon=-13)
    
    x, y = M(lons, lats) # transform coordinates according to projection
    boxes = []
    for xa, ya, name in zip(x, y, names):
        box = plt.text(xa, ya, name,
            bbox=dict(facecolor='white', alpha=0.5))
        boxes.append(box)
    
    M.bluemarble() # a bit fuzzy at this resolution...
    
    # predefine padding in inches
    PADDING = 2
    # force dpi to same value you used in your calculations
    plt.savefig('test.png', bbox_inches="tight", pad_inches=PADDING,dpi=FIGDPI)
    
    # document shift due to loss of white space and added padding
    origin = plt.gca().transAxes.transform((0,0))
    padding = [FIGDPI*PADDING,FIGDPI*PADDING]
    

    Step #2 is unchanged

    Step #3 takes account of the origin

    # Step 3: use PIL to draw dots on top of the labels
    from PIL import Image, ImageDraw
    
    im = Image.open("test.png")
    draw = ImageDraw.Draw(im)
    for x, y in midpoints:
        #  deal with shift
        x = x-origin[0]+padding[0]
        y = y-origin[1]+padding[1]
        y = im.size[1] - y # PIL counts rows from top not bottom
        draw.ellipse((x-5, y-5, x+5, y+5), fill="#ff0000")
    im.save("test.png", "PNG")
    

    This results in:

    enter image description here

    Notice that I used an exaggerated PADDING value to test that everything still works, and a value of 0.01 would produce your original figure.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM
I need to convert HTML documents into valid XML, preferably XHTML. What's the best
I need to convert a Word document into HTML file(s) in Java. The function
I need to map class A into class C using dozer framework. public class
I need to convert a value which is in a DateTime variable into a
I need to convert an arbitrary amount of milliseconds into Days, Hours, Minutes Second.
I need to convert → (&rarr) to a symbol I can type into a
I need to somehow convert a single json string into multiple objects of a
I am using Jackson to serialize a JAXB annotated object into a map object.
I need to convert fixnums to strings. My solution is: arr.map {|a| a.to_s} Is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.