I want to add an ability to drag and drop two markers to a google map, get their longitude and latitude and send it to the backend server.The initial position for those markers must be in a fixed points, to illustrate this imagine the following box as the div that contains the google map
+++++++++++++++++++++
| |
| X |
| |
| |
| Y |
+++++++++++++++++++++
The X
and Y
represent the initial locations of the two markers. The problems that I am facing are:
div
that contains them. The markers must be located according to longitude and latitude. How to set the markers in a fixed positions according to the div itself, not to the longitude and latitude of the earth? Is there a way to map the pixel locations of a google map to longitude and latitude?
To do this transformation you will have to calculate the bounds of your div and the displayed area on the map in their own coordinate reference systems. Then you can transform your x/y coordinates this way:
// Get the div's bounds
var divMap = document.getElementById('map');
var height = divMap.offsetHeight;
var width = divMap.offsetWidth;
// Get the map's bounds
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
// Latitude-pixel ratio
var ratioLat = (ne.lat() - sw.lat()) / height;
// Longitude-pixel ratio
var ratioLng = (ne.lng() - sw.lng()) / width;
// Transform the x/y coordinates to lat/lng coordinates
// Assuming that you already have the relative x and y coordinates in your div
var transLat = y * ratioLat + sw.lat();
var transLng = x * ratioLng + sw.lng();
//OR you can do this
var transLat = ne.lat() - y * ratioLat;
var transLng = ne.lng() - x * ratioLng;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.