Reputation: 1371
So I have a map and a form, once user fills in address + postcode it puts a marker to the map, however I want to make it draggable and keep a value of lat and long.
For some reason, I cannot move the marker why?
JS:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('postcode').addEventListener('blur', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address2').value +','+ document.getElementById('postcode').value;
console.log(address);
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: address,
draggable:true,
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
currentLatitude = latLng.lat();
currentLongitude = latLng.lng();
jQ("#latitude").val(currentLatitude);
jQ("#longitude").val(currentLongitude);
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
Upvotes: 1
Views: 549
Reputation: 133370
You should declare the var map at window level
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
.....
then in you geocodeAddress function you should refer to map for marker map
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address,
draggable:true,
});
looking to your code the marker don't should be placed on map because you refer resultsMap
Upvotes: 2