JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<h1>Draggable Marker Confined to a Polyline</h1>
<hr/>
<p>
Grab and drag the marker left and right. It will "stick" to the polyline". If you manage to move it off the polyline somehow it should snap to the closest point on the line when you drop it</p>
<hr/>
<div id="map-canvas" style="width:500px;height:500px"></div>
CSS
h1{
font-family:arial,helvetica,sans-serif;
font-size:20px;
font-weight:bold;
}
p{
font-family:arial,helvetica,sans-serif;
}
JavaScript
var padded_points = new Array(); //To store the padded array of points
var map;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(-36.86501268451408, 174.723858833313),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var latLng = new google.maps.LatLng(-36.8656740244478, 174.72489793784916);
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true
});
google.maps.event.addDomListener(marker, 'dragend', function(e) {
marker.setPosition(find_closest_point_on_path(e.latLng,padded_points));
});
google.maps.event.addDomListener(marker, 'drag', function(e) {
marker.setPosition(find_closest_point_on_path(e.latLng,padded_points));
});
}
$(function() {
initialize();
//I grab these points from a GPX file but have used dummy points here
var array_of_points_to_pad = new Array(
new google.maps.LatLng(-36.8656740244478, 174.72489793784916),
new google.maps.LatLng(-36.86582762282342, 174.72503422759473),
new google.maps.LatLng(-36.865929337218404, 174.72529197111726),
new google.maps.LatLng(-36.86608469579369, 174.72548073157668),
new google.maps.LatLng(-36.866103052161634, 174.72563814371824),
new google.maps.LatLng(-36.8661513319239, 174.7257921192795),
new google.maps.LatLng(-36.86634725891054, 174.72605866380036),
new google.maps.LatLng(-36.86636704020202, 174.72634574398398),
new google.maps.LatLng(-36.86640760861337, 174.72647675313056),
new google.maps.LatLng(-36.866334015503526, 174.7267128713429),
new google.maps.LatLng(-36.86633242294192, 174.72689299844205)
);
//Pad the...