How To Add Marker On Google Map With Two Locations?
I would like to add markers on google map with two locations, that are clickable. When I click on the button it should change the map marker with the location.
Solution 1:
var map = nullvar marker = null;
var myLatLng = {
lat: 52.302516,
lng: 16.414546
};
functioninitMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(myLatLng.lat, myLatLng.lng),
zoom: 14,
});
marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
functionupdateMap(lat, lng) {;
myLatLng.lat = lat;
myLatLng.lng = lng
map.setCenter(myLatLng);
marker.setPosition(myLatLng);
}
$(document).ready(function() {
$("#1").on('click', function() {
updateMap(52.302516, 16.414546);
});
$("#2").on('click', function() {
updateMap(51.706478, 15.274753);
});
});
I am initing the map with new marker. Working jffiddle is here
Solution 2:
this function will only switch the location of the view:
map.setCenter({lat:newLat,lng:newLng});
use this instead:
new google.maps.LatLng(-25.363882,131.044922);
secondly to you need to add event listner to the marker object for it to work properly:
// create markers on the map
marker1 = new google.maps.Marker({ ... })
marker2 = new google.maps.Marker({ ... })
marker3 = new google.maps.Marker({ ... })
// add event listener
marker1.addListener('click', function() { ... })
marker2.addListener('click', function() { ... })
further check out the docs they are pretty straight forward.
Solution 3:
This will work. Have a global variable that holds the marker
. Whenever the location is changed, set the marker in the position of Lat
and Lng
using the setPosition
method and use setCenter
method to show the marker in the center. No need to init the map every time.
var map,marker;
functioninitialize()
{
map = new google.maps.Map(document.getElementById('googleMap'), {
center: new google.maps.LatLng(52.302516, 16.414546), //Setting Initial Positionzoom: 6,
});
setLocation(52.302516,16.414546);
}
functionsetLocation(newLat, newLng)
{
var latlng = new google.maps.LatLng(newLat,newLng);
if(marker) //Remove the marker, if already set
{
marker.setMap(null);
}
marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'AGM-CORP'
});
map.setCenter(latlng);
}
$(document).ready(function ()
{
$("#1").on('click', function ()
{
setLocation(13.070814558816117, 80.2656996835234);
});
$("#2").on('click', function ()
{
setLocation(59.4739316352335,-110.89646088128342);
});
});
Post a Comment for "How To Add Marker On Google Map With Two Locations?"