I added jquery geocomplete to my app.
$("address").geocomplete();
And it works.
But I also want to link this with the map that I already have on the page:
<div id="map2"></div>
$("#address").geocomplete({
map: "#map2"
});
But for some reason, when updating the field address
, the map is not updated.
Javascript, which i use for map:
<script>
function initMap2() {
var lat = document.getElementById('course_latitude').value;
var lng = document.getElementById('course_longitude').value;
// if not defined create default position
if (!lat || !lng){
lat=51;
lng=49;
document.getElementById('course_latitude').value = lat;
document.getElementById('course_longitude').value = lng;
}
var myCoords = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: myCoords,
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map2'), mapOptions);
var marker = new google.maps.Marker({
position: myCoords,
animation: google.maps.Animation.DROP,
map: map,
draggable: true
});
// refresh marker position and recenter map on marker
function refreshMarker(){
var lat = document.getElementById('course_latitude').value;
var lng = document.getElementById('course_longitude').value;
var myCoords = new google.maps.LatLng(lat, lng);
marker.setPosition(myCoords);
map.setCenter(marker.getPosition());
}
// when input values change call refreshMarker
document.getElementById('course_latitude').onchange = refreshMarker;
document.getElementById('course_longitude').onchange = refreshMarker;
// when marker is dragged update input values
marker.addListener('drag', function() {
latlng = marker.getPosition();
newlat=(Math.round(latlng.lat()*1000000))/1000000;
newlng=(Math.round(latlng.lng()*1000000))/1000000;
document.getElementById('course_latitude').value = newlat;
document.getElementById('course_longitude').value = newlng;
});
// When drag ends, center (pan) the map on the marker position
marker.addListener('dragend', function() {
map.panTo(marker.getPosition());
});
}
document.addEventListener("DOMContentLoaded", initMap2);
</script>
UPDATE
How i load google maps:
<script type="text/javascript" src="<%= "https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_MAPS_API_KEY']}&libraries=places" %>"></script>
UPDATE 2. As I understand it, the problem is in these lines:
var lat = document.getElementById('course_latitude').value;
var lng = document.getElementById('course_longitude').value;
If I delete them and start entering the address, the map will be updated.
But also, if I delete these lines, the map will not be visible until the address is entered. Just a gray square.
How can i fix this?