简体   繁体   中英

Draw marker on Google Map at specific positions

I have created a small tool using Google map API javascript. It takes the place name as input and when form is submitted, it places marker at that location. That's very basic usage. But what I want to achieve is,

  1. take that location's latitude-longitude as base and make it as marker in center(which is done already)

  2. place one marker 10 miles away from center to the top position

  3. Place one marker 10 miles away from center to the bottom position

  4. Place one marker 10 miles away from center to the left position

  5. Place one marker 10 miles away from center to the right position

So basically there will be total 5 markers. one in center and 4 on top, bottom, left and right position at exactly 10 miles distance. How can I do that?

The Google Maps JS API has a Geometry library. You need to include it in the API call:

https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry

The spherical namespace contains a computeOffset() method which allows to pass your coordinates, a distance and a heading.

0/360° = North, 90° = East, 180° = South, etc.

So if you want to compute a point at 10 km East from the coordinates 0,0 you can do:

let point = google.maps.geometry.spherical.computeOffset(new google.maps.LatLng(0,0), 10000, 90);

Distance is passed in meters so you can simply multiply your distance in miles by 1609,34 .

More information here: https://developers.google.com/maps/documentation/javascript/geometry#Geometry

Proof of concept:

 var map; function initMap() { let center = new google.maps.LatLng(53.051185, -2.492474); map = new google.maps.Map(document.getElementById('map-canvas'), { zoom: 13, center: center }); var marker = new google.maps.Marker({ position: center, map: map, }); addMarker(center, 1000, 0); addMarker(center, 1000, 90); addMarker(center, 1000, 180); addMarker(center, 1000, 270); } function addMarker(coords, offset, heading) { let point = google.maps.geometry.spherical.computeOffset(coords, offset, heading); var marker = new google.maps.Marker({ position: point, map: map, }); } initMap(); 
 #map-canvas { height: 200px; } 
 <div id="map-canvas"></div> <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM