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.
<script>
var map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(52.302516, 16.414546), //Setting Initial Position
zoom: 14,
});
var marker = new google.maps.Marker({
position: newLocation(),
map: map,
title: 'AGM-CORP',
icon: 'img/agm-marker.png'
});
}
function newLocation(newLat, newLng)
{
map.setCenter({
lat: newLat,
lng: newLng
});
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function ()
{
$("#1").on('click', function ()
{
newLocation(52.302516, 16.414546);
});
$("#2").on('click', function ()
{
newLocation(51.706478, 15.274753);
});
});
</script>
<div id="map-canvas"></div>
</div>
<h3>Zobacz lokalizację:</h3>
<button id="1" style="padding:10px; cursor:pointer;">Siedziba Firmy</button>
<button id="2" style="padding:10px;cursor:pointer;">Kopalnia Kruszyw</button>
</div>
I am initing the map with new marker. Working jffiddle is here
this function will only switch the location of the view:
use this instead:
secondly to you need to add event listner to the marker object for it to work properly:
further check out the docs they are pretty straight forward.
This will work. Have a global variable that holds the
marker
. Whenever the location is changed, set the marker in the position ofLat
andLng
using thesetPosition
method and usesetCenter
method to show the marker in the center. No need to init the map every time.