Convert longitude/latitude to x/y on iPhone

后端 未结 1 1633
名媛妹妹
名媛妹妹 2020-12-31 22:22

I am showing an image in an UIImageView and i\'d like to convert coordinates to x/y values so i can show cities on this image. This is what i tried based on my research:

相关标签:
1条回答
  • 2020-12-31 23:02

    To make this work you need to know 4 pieces of data:

    1. Latitude and longitude of the top left corner of the image.
    2. Latitude and longitude of the bottom right corner of the image.
    3. Width and height of the image (in points).
    4. Latitude and longitude of the data point.

    With that info you can do the following:

    // These should roughly box Germany - use the actual values appropriate to your image
    double minLat = 54.8;
    double minLong = 5.5;
    double maxLat = 47.2;
    double maxLong = 15.1;
    
    // Map image size (in points)
    CGSize mapSize = mapView.frame.size;
    
    // Determine the map scale (points per degree)
    double xScale = mapSize.width / (maxLong - minLong);
    double yScale = mapSize.height / (maxLat - minLat);
    
    // Latitude and longitude of city
    double spotLat = 49.993615;
    double spotLong = 8.242493;
    
    // position of map image for point
    CGFloat x = (spotLong - minLong) * xScale;
    CGFloat y = (spotLat - minLat) * yScale;
    

    If x or y are negative or greater than the image's size, then the point is off of the map.

    This simple solution assumes the map image uses the basic cylindrical projection (Mercator) where all lines of latitude and longitude are straight lines.

    Edit:

    To convert an image point back to a coordinate, just reverse the calculation:

    double pointLong = pointX / xScale + minLong;
    double pointLat = pointY / yScale + minLat;
    

    where pointX and pointY represent a point on the image in screen points. (0, 0) is the top left corner of the image.

    0 讨论(0)
提交回复
热议问题