I'm trying to create a map that is able to track my location and at the same time be able to display multiple markers. Am I able to combine the 2 JavaScript below? If not any idea on how I should do it?
JavaScript for multiple markers
<script type="text/javascript">
var locations = [
['Hougang', 1.37265, 103.893658],
['Punggol', 1.400617, 103.907833],
['MacRitchie Reservoir', 1.346002, 103.825436],
['Bishan', 1.352051, 103.849125],
['Sentosa', 1.251226, 103.830757]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(1.37265, 103.893658),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
JavaScript for current location
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
Yes, it is possible to combine the two. When you initialize the map and after plotting the Hougang... locations you can add the geolocation code. I wrote a demo that will show a smaller green icon for the geolocation. If the browser doesn't support geocoding nothing will appear, no errors will show either.
DEMO http://jsfiddle.net/yV6xv/7/
Keep in mind the geolocation does not work (for me at least) if the code is loaded locally from the hard drive. It must be served publicly.
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 8,
center: geolocpoint,
mapTypeId: google.maps.MapTypeId.HYBRID
}
// Place a marker
var geolocation = new google.maps.Marker({
position: geolocpoint,
map: map,
title: 'Your geolocation',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With