all. Please help me solve this issue. Currently I have a dropdown of multiple location for google map. But the marker keeps on duplicating when I change the location. Here is the code for google map. I would like the map to clear the previous marker and only display marker on the current selected location
var geocoder;
var map;
var marker;
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(4.2105,101.9758),
zoom: 6.5
};
map = new google.maps.Map(mapCanvas, mapOptions);
geocoder = new google.maps.Geocoder();
google.maps.event.addDomListener(window, "load", initMap);
}
function geocodeAddress(location) {
var address = '';
if (location != 'all') {
var resultFromAjax = $.ajax({
type: 'POST',
url: "{{ route('getLocation') }}",
data: {
id: location
},
success: function (response) {
if (response.location != '') {
address = response.location;
}
},
error: function (xhr) {
console.log(xhr);
},
async: false
});
}
else {
address = 'Malaysia';
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
console.log(marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
I have found the solution, instead of locally declare the marker, I set it as a global function before populate it based on location using geocoding.
var geocoder;
var map;
var marker;
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(4.2105,101.9758),
zoom: 6.5
};
map = new google.maps.Map(mapCanvas, mapOptions);
geocoder = new google.maps.Geocoder();
//Marker
marker = new google.maps.Marker();
marker.setPosition(map.getCenter());
marker.setMap(map);
//
google.maps.event.addDomListener(window, "load", initMap);
}
function geocodeAddress(location) {
var address = '';
if (location != 'all') {
var resultFromAjax = $.ajax({
type: 'POST',
url: "{{ route('getLocation') }}",
data: {
id: location
},
success: function (response) {
if (response.location != '') {
address = response.location;
}
},
error: function (xhr) {
console.log(xhr);
},
async: false
});
}
else {
address = 'Malaysia';
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
marker.setOptions({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
// var marker = new google.maps.Marker({
// map: map,
// animation: google.maps.Animation.DROP,
// position: results[0].geometry.location
// });
console.log(marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
Related
I have the old infowindows in a loop problem where the content for the last loop is showing in all infowindows. Yes I know there are several questions about this already on Stack Overflow but none of them seem to work for me.
<script>
var map;
var myMarker = [];
var myData = [];
function initialize() {
var Nazareth = { lat: -29.847073, lng: 30.853513 };
var myCenter = new google.maps.LatLng(-29.847073, 30.853513);
var mapOptions = {
center: Nazareth,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
SetMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow = new google.maps.InfoWindow();
function SetMarkers() {
var geocoder = new google.maps.Geocoder();
$('#btnTrainer').click(function () {
var suburb = $("#address").val();
$.ajax({
type: "POST",
url: '#Url.Action("ShowAll", "Map")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "suburb": suburb }),
cache: false,
dataType: "json",
success: function (myData) {
for (i = 0; i < myData.length; i++) {
var data = myData[i];
var name = myData[i].FirstName;
var address = myData[i].Address;
geocoder.geocode({ 'address': data.Address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "Trainer" + " "
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(name + "," + address);
infoWindow.open(map, marker);
}
})(marker, i));
}
else {
console.log("We can't found the address, GoogleMaps say..." + status);
}
});
};
}
})
})
}
</script>
I've got problems to put links on multiple markers, I can show my markers on the map, but when a I try tu put link on them, I have always the same link on all markers, the last. Here I provide a sample code:
<div id="map" style="height: 400px; width:100%;"></div>
<script>
var markers = [{"name":"Vasto","url":"http://www.google.com"},{"name":"Chieti","url":"http://www.wikipedia.com"}];
var geocoder;
var map;
var LatLng;
var url;
console.log(markers);
function initMap() {
LatLng = {lat: 42.2872297, lng: 13.3403448};
map = new google.maps.Map(document.getElementById('map'), {zoom: 8, center: LatLng});
geocoder = new google.maps.Geocoder();
setMarkers();
}
function setMarkers() {
var marker, i, url;
for( i = 0; i < markers.length; i++ ) {
url = markers[i].url;
geocoder.geocode({'address': markers[i].name}, function(results, status) {
if (status === 'OK') {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap" async defer></script>
Any solutions?
Thanks in advance
Due to asynchronous code, you need to change your code a bit
function setMarkers() {
markers.forEach(function(item) {
var url = item.url;
geocoder.geocode({'address': item.name}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}
I want to add this forecast to the infowindow. I wanna use Google weather layers. But i dont know how to put them to the current infowindow
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
var cloudLayer = new google.maps.weather.CloudLayer();
How can i add forecast to the current info window, after details of location?
Thank you
function showPosition(position) {
var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: googlePos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapObj = document.getElementById('divmap');
var googleMap = new google.maps.Map(mapObj, mapOptions);
var markerOpt = {
map: googleMap,
position: googlePos,
title: 'Hi , I am here',
animation: google.maps.Animation.DROP
};
var googleMarker = new google.maps.Marker(markerOpt);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': googlePos
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var popOpts = {
content: results[1].formatted_address,
position: googlePos
};
var popup = new google.maps.InfoWindow(popOpts);
/*google.maps.event.addListener(googleMap, 'center_changed', function(){
window.setTimeout(function(){
googleMap.panTo(googleMarker.getPosition());
}, 2000);
});*/
google.maps.event.addListener(googleMarker, 'setTimeout', setTimeout(function () {
popup.open(googleMap, googleMarker)
}, 200));
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
I have a webpage to find latitude, longitude, and get a marker for that position. I use Google Maps.
My webpage get 2 addresses from user input, address 1 and address 2, and calls codeAddress()
<div id="panel">
<input id="address1" type="textbox" value="">
<input id="address2" type="textbox" value="">
<input type="button" value="find!" onclick="codeAddress()">
</div>
This is my JavaScript code:
var map;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var gc = google.maps.Geocoder();
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
}
When I click the button find, I didn’t get the markers. Can any body help me?
Modify the codeAddress function like this:
function codeAddress() {
var gc = new google.maps.Geocoder(); // notice new keyword
initialize(); // Calling initialize. If you skip it, maps aren't loading
gc.geocode({
'address': address1
}, function(res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function(res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
Make sure both of the inputs have some value to test it.
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/213/
update the address variables from the form when the function runs
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
check for status != OK
} else alert("Geocode failed of " + address1 + ", status=" + status);
use "new" before the google maps Geocoder constructor
var gc = new google.maps.Geocoder();
remove existing markers before displaying new ones so the markers don't accumulate on the map
if (marker1 && marker1.setMap) marker1.setMap(null);
complete code:
var map = null;
var marker1 = null;
var marker2 = null;
var gc = new google.maps.Geocoder();
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker1 && marker1.setMap) marker1.setMap(null);
marker1 = new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
if (marker2 && marker2.setMap) marker2.setMap(null);
marker2 = new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
} else alert("Geocode failed of " + address2 + ", status=" + status);
});
} else alert("Geocode failed of " + address1 + ", status=" + status);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working fiddle
I've spent the last 8 hours trying to do something extremelly easy.
The problem is that I'm not very familiar with JavaScript neither Google Maps API.
All I want to do is to find the center of 2 different locations and zoom accordly.
The 2 address are dinamically, since the user will input the info.
All my searched ended on API v2 or for fixed locations.
Could someone please help me out?
I really appreciate it!
Thanks a lot in advance!!!
<script src="https://maps.googleapis.com/maps/api/js?sensor=false®ion=BR"></script>
<script>
var geocoder;
var map;
var query = "<?php echo $endCercompleto; ?>";
var query2 = "<?php echo $endFescompleto; ?>";
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom:8,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
var address = query;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var address2 = query2;
geocoder.geocode( { 'address': address2}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
</script>
This should work. Note that the bounds.extend and the map.fitBounds in each of the geocoder callback routines. You don't know which will complete first.
proof of concept fiddle
<script src="https://maps.googleapis.com/maps/api/js?region=BR"></script>
<script>
var geocoder;
var bounds = new google.maps.LatLngBounds();
var map;
var query = "<?php echo $endCercompleto; ?>";
var query2 = "<?php echo $endFescompleto; ?>";
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom:8,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
var address = query;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var address2 = query2;
geocoder.geocode( { 'address': address2}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
var marker2 = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>