Search code examples
javascripthtmlgoogle-mapslatitude-longitude

google map get latitude, longitude from pixel x,y


I want to get the coordinates of the place I want on my map. If you select a point of x:400px, y:400px in a map of size 500px * 500px like the example in the code below, you want to get the latitude and longitude there. I can now implement this via click event. But what I want is to use it through a method, not through an event. For example, if I give x:240px, y:300px as parameters, I want to return (latitude: 35.61823, longitude: 125.142314) regardless of the shape. The code below implements this as a click event.

<!DOCTYPE html>
<html>
<head>
  <title>Getting Properties With Event Handlers</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
    defer></script>
  <script>
    function initMap() {
      var seoul = { lat: 37.56532723199129, lng: 126.98799094110187 };
      const map = new google.maps.Map(
        document.getElementById("map"), {
        zoom: 15,
        center: seoul,
      });
      map.addListener("click", (mapsMouseEvent) => {
        console.log(mapsMouseEvent.pixel)
        console.log(mapsMouseEvent.latLng.toJSON())
      });
    }
  </script>
</head>
<body>  
    <div id="map" style = "width:500px; height:500px;"></div>
</body>
</html>

Solution

  • related question: Google Maps: Get click or marker (x,y) pixel coordinates inside marker click listener

    Note that the center of the map (atitude: 35.61823, longitude: 125.142314) is at (x:250px, y: 250px), not at (x:240px, y:300px)

    Use the fromContainerPixelToLatLng method to translate container pixels to geographic coordinates.

    To get access to the MapCanvasProjection, make an instance of the OverlayView class, and call getProjection on that.

    google.maps.event.addListener(map, 'projection_changed', function() {
      overlay = new google.maps.OverlayView();
      overlay.draw = function() {};
      overlay.setMap(map);
      google.maps.event.addListener(overlay, 'projection_changed', function() {
        // x:240px, y:300px as parameters, I want to return (latitude: 35.61823, longitude: 125.142314) 
        var latLng = overlay.getProjection().fromContainerPixelToLatLng(new google.maps.Point(250, 250));
        console.log(latLng.toUrlValue(6));
      })
    })
    

    code snippet:

    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Getting Properties With Event Handlers</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
      <script>
        function initMap() {
          var seoul = {
            lat: 37.56532723199129,
            lng: 126.98799094110187
          };
          const map = new google.maps.Map(
            document.getElementById("map"), {
              zoom: 15,
              center: seoul,
            });
          google.maps.event.addListener(map, 'projection_changed', function() {
              overlay = new google.maps.OverlayView();
              overlay.draw = function() {};
              overlay.setMap(map);
              google.maps.event.addListener(overlay, 'projection_changed', function() {
                // x:240px, y:300px as parameters, I want to return (latitude: 35.61823, longitude: 125.142314) 
                var latLng = overlay.getProjection().fromContainerPixelToLatLng(new google.maps.Point(250, 250));
                console.log(latLng.toUrlValue(6));
              })
           })
    
            map.addListener("click", (mapsMouseEvent) => {
              console.log(mapsMouseEvent.pixel)
              console.log(mapsMouseEvent.latLng.toJSON())
            });
          }
      </script>
    </head>
    
    <body>
      <div id="map" style="width:500px; height:500px;"></div>
    </body>
    
    </html>