Search code examples
phpjavascriptcoordinateslatitude-longitudegeocode

Convert lat/long to pixel X&Y co-ordinates


This type of question seems to have been asked numerous times but none of the solutions posted get me anywhere near the answer I need.

I have this map of Northland, New Zealand and I'd like to map Lat/Long values to x/y (pixel) values on this image (https://i.sstatic.net/3ok4O.gif - which is 400px square)

Right now I do not know the precise lat/long boundaries of this image, but I do have some example data which should be useful to someone who knows what they are doing.

  LAT              LONG            X                Y
  -35.3989854471   173.504676819   192.92777494     196.760481649
  -35.2647882735   174.121499062   271.426291418    176.82865668
  -35.3131641432   173.89125824    242.099305271    183.945780963

The data I'm receiving now is only Lat/long, so I need to be able to produce x and y values within the application.

Can anybody help me write the required method/logic for creating these x/y values.

Thank you!


Solution

  • in Javascript....

    var lat=-35.3989854471;
    var long=173.504676819;
    
    var imageNorthLat=???;
    var imageSouthLat=???;
    
    var imageWestLong=???;
    var imageEastLong=???;
    
    var imageLongPixels=400;
    var imageLatPixels=400;
    
    var pixelsPerLat=imageLatPixels/(imageNorthLat-imageSouthLat);
    var pixelsPerLong=imageLongPixels/(imageEastLong-imageWestLong);
    
    var xPixelPosition=(long-imageWestLong)*pixelsPerLong;
    var yPixelPosition=Math.abs(lat-imageNorthLat)*pixelsPerLat;
    

    I didn't try to run this, so there's probably a bit of debugging necessary, and the x and y pixel positions would have to have added to them the x and y positions of the top left or your map. But you can see the idea. And, of course, I may not have understood what you're really asking.