Reputation: 321
On a personal blog website I am making, I have the background set as the google map and have a smaller div on top talking about places I've been to etc. What I want to do is have a link like "show place in google map" and when clicked, the background map will be updated to the corresponding location.
I tried making a javascript code
<script> function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
scrollwheel: false,
center: new google.maps.LatLng(34.0722, -118.4441),
zoom: 14,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
streetViewControl: false,
panControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
window.onload = function() {
var a = document.getElementsByClassName("map-link");
a.onclick = function() {
marker.setMap(map);
}
}
</script>
<a class="map-link" href="javascript:void(0)"> Show in Google Maps </a>
Something like this, but I'm not seeing any result. Does anybody know how to go about this?
Upvotes: 0
Views: 236
Reputation: 161334
map.setCenter
to change the center of the map.getElementsByClassName returns an array of DOM elements.
google.maps.event.addDomListener(document.getElementsByClassName("map-link")[0], 'click', function (e) { map.setCenter(new google.maps.LatLng(42, -72)); });
code snippet:
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
scrollwheel: false,
center: new google.maps.LatLng(34.0722, -118.4441),
zoom: 14,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
streetViewControl: false,
panControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addDomListener(document.getElementsByClassName("map-link")[0], 'click', function(e) {
map.setCenter(new google.maps.LatLng(42, -72));
});
google.maps.event.addDomListener(document.getElementsByClassName("map-link")[1], 'click', function(e) {
map.setCenter(new google.maps.LatLng(41, -72.1));
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<ul>
<li><a class="map-link" href="javascript:void(0)"> Show in Google Maps </a>
</li>
<li><a class="map-link" href="javascript:void(0)"> Show another place in Google Maps </a>
</li>
</ul>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>
Upvotes: 1