Google Maps Api Get Lat And Lng And Replace Marker?
So at the moment when user enter address it adds the marker which is fine, user can also move the marker to a new location and retrieve it's lat and lng. However what it doesn't do
Solution 1:
You can declare a global variable marker
, and set marker's map is null
var map;
var marker;
functioninitMap() {
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('keyup', function()
{
geocodeAddress(geocoder, map);
});
}
functiongeocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address1').value + '\xa0' +
document.getElementById('address2').value +','+
document.getElementById('postcode').value;
console.log(address);
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
//if marker exist, replace it if not create it.
map.setCenter(results[0].geometry.location);
if(marker && marker instanceof google.maps.Marker){
marker.setMap(null);
marker = null;
}
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address,
draggable:true,
//get lng and lat and save it to 2 seperate variables?
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
currentLatitude = latLng.lat();
currentLongitude = latLng.lng();
console.log(currentLatitude);
console.log(currentLongitude);
$("#latitude").val(currentLatitude);
$("#longitude").val(currentLongitude);
});
} else {
$('#error').append('<div class="alert alert-danger">Address not
found please try again</div>');
$(".alert-danger").fadeOut(5000);
}
});
}
Solution 2:
for Get lat and lng from the address (when pin is added to page) you can
lat = results[0].geometry.location.lat();lng = results[0].geometry.location.lng();
for change the marker instead of create a new one you can define a globale (window level ) var marker and assign eve to this var the result for marker creation remember tor setMap(null) for hide the old marker
var marker;
varmap;
if (marker != null) {
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address,
draggable:true,
//get lng and lat and save it to 2 seperate variables?
});
Post a Comment for "Google Maps Api Get Lat And Lng And Replace Marker?"