Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 96 You must be signed in to star a gist
  • Fork 50 You must be signed in to fork a gist
  • Save parth1020/4481893 to your computer and use it in GitHub Desktop.
Save parth1020/4481893 to your computer and use it in GitHub Desktop.
Google Maps Simple Multiple Marker Example
<html>
<head>
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="map" style="height: 400px; width: 500px;">
</div>
<script type="text/javascript">
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
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));
}
</script>
</body>
</html>
Copy link

ghost commented Jul 15, 2016

So, this code is add marker but not runtime.(ex: I have a coordinate list, i want add when someone pressing the button(on existing map))

@hridesh123
Copy link

your code is explained beautifully but can you tell us how do we get the locations dynamically to mark at map....as you have used locations statically..

@kyriolexy16
Copy link

Thanks for the code! :)

@nhantam
Copy link

nhantam commented Sep 30, 2016

Example clearly ... Thanks a lot

@candiceherrera
Copy link

Perrrrfect! Clean and super easy!

@simplix-fr
Copy link

Thnx ;-)

@JustinRyanCarlson
Copy link

Thanks so much for this, it worked great.

@rajananimator
Copy link

Great! Thanks for sharing.

@aakash1147
Copy link

aakash1147 commented May 25, 2017

this is excellent but i want to get custom marker instead of default marker according to the country where the marker is been placed
..... who do i will get it.....plz mail me the code for this at my emailid aakash1147@live.com

@Saif-rahman
Copy link

Works well. Thanks for sharing.

@joesebastian6079
Copy link

hi, just tried this. On the whole everything is working perfectly, but its only showing 4 pins. I need to show 17. Any idea??

@LC43
Copy link

LC43 commented Jul 22, 2017

@joesebastian6079, just duplicate the first location coordinates.

@RCAVelez
Copy link

@LC43 what do you mean by duplicate the first location coordinates?

@dodyan
Copy link

dodyan commented Oct 19, 2017

You are awesome ! thx 4 sharing ! :)

@IshratSapphire
Copy link

Thanks

@creativecoder567
Copy link

thanks

@deepakparamesh
Copy link

deepakparamesh commented Mar 11, 2018

Hi,
This is my angular 4 script, I am getting the markers but I am not getting the Infowindow when I click the markers.
`ngOnInit() {
let map;

var mapProp = {
  center: new google.maps.LatLng(35.9375, 14.3754),
  zoom: 11,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(this.gmapElement.nativeElement,mapProp);

this.restaurants = this.restaurantService.getLatLan();
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i=0; i<this.restaurants.length; i++){

   marker = new google.maps.Marker({
    position: new google.maps.LatLng(Number(this.restaurants[i].latitude), Number(this.restaurants[i].longitude)),
    map: map,
    title: this.restaurants[i].name,
  });
  
  //place marker in map
  marker.setMap(this.map)

  google.maps.event.addListener(marker, 'click', (function(marker, i){
    return function(){
      infowindow.setContent(this.restaurants[i].name);
      infowindow.open(map, marker)
    }
  }) (marker, i));

}

}`

Please someone find if anything wrong, Thanks in advance.

@munnangiramya
Copy link

thanku soo much........

@vijaybhat1981
Copy link

i have a code which finds my current position and mark it with marker and now i had another position which is hard coded and it is to be marked in map, but when i run program it shows marker at my current position only and then calculate distance netween my current position and and the hard coded position which is working fine.
Problems:
1.Only one marker is shown
2. The shortest root between them is not highlighted.
now i am pasting my code please help me in this as i am new to ASP.net
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="myloc.aspx.cs" Inherits="Radiant_Loc_Tracer.myloc" %>

<title></title> <%--<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>--%> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDHVwlYQWZzZbj6iNo_ryUqt-amDk8CTyU&callback=initMap" type="text/javascript"></script> <script type="text/javascript"> if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (p) { var cur_loc = (p.coords.latitude + "," + p.coords.longitude); var indiagate = ("28.6109" + "," + "77.2344");//cordinates if India Gate var com_cord = indiagate + ":" + cur_loc; var indcord = com_cord.split(":"); for (var i = 0; i < indcord.length; i++) { var ncord_cord = (indcord[i]); var split_fincord = ncord_cord.split(","); var finalcordinates = "(" + parseFloat(split_fincord[0]) + "," + parseFloat(split_fincord[1]) + ")"; var data = indcord[i]; var LatLng = new google.maps.LatLng(parseFloat(split_fincord[0]), parseFloat(split_fincord[1])); var mapOptions = { center: LatLng, zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); var marker = new google.maps.Marker({ position: LatLng, map: map, //title: "
Your location:
Latitude: " + parseFloat(split_fincord[0]) + "
Longitude: " + parseFloat(split_fincord[1]) title: "Latitude: " + parseFloat(split_fincord[0]) + "Longitude: " + parseFloat(split_fincord[1]) }); google.maps.event.addListener(marker, "click", function (e) { var infoWindow = new google.maps.InfoWindow(), marker, data; infoWindow.setContent(marker.title); infoWindow.open(map, marker); }); } var newlocstring = com_cord.replace(":", ","); //alert (newlocstring); var new_pts = newlocstring.split(","); var d = getDistanceFromLatLonInKm(new_pts[0], new_pts[1], new_pts[2], new_pts[3]); //alert(d); document.getElementById('<%=lbl1.ClientID%>').textContent = d.toFixed(2) + "Km"; calcRoute(new_pts[0], new_pts[1], new_pts[2], new_pts[3]) }); } else { alert('Geo Location feature is not supported in this browser.'); } function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) { var R = 6371; // Radius of the earth in km var dLat = deg2rad(parseFloat(lat2) - parseFloat(lat1)); // deg2rad below var dLon = deg2rad(parseFloat(lon2) - parseFloat(lon1)); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(parseFloat(lat1))) * Math.cos(deg2rad(parseFloat(lat2))) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; // Distance in km return d; } function deg2rad(deg) { return deg * (Math.PI / 180) } function calcRoute(lat1, lon1, lat2, lon2) { var start = new google.maps.LatLng(parseFloat((lat1)), parseFloat(lon1)); var end = new google.maps.LatLng(parseFloat(lat2), parseFloat(lon2)); var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING }; directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); }; </script>
<form id="loctracer" runat="server">
    <div><asp:Label runat="server" ID="Label2" Font-Bold="true" Font-Size="Large" BackColor="#0000ff" ForeColor="White"> RADIANT TECHNOLOGIES</asp:Label></div>
    <div id="dvMap" style="width: 500px; height: 500px">
    </div>
    <div><asp:Label runat="server" ID="Label1" Font-Bold="true" Font-Size="Large">Distance Between Your Location And India Gate Is :</asp:Label></div>
    <div><asp:Label runat="server" ID="lbl1" Font-Bold="true" Font-Size="Large"> </asp:Label></div>

</form>

my email id is vijaybhat1981@gmail.com

@bhadreshbbb3
Copy link

jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});

function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
    
// Multiple Markers
var markers = [
    ['London Eye, London', 51.503454,-0.119562],
    ['Palace of Westminster, London', 51.499633,-0.124755]
];
                    
// Info Window Content
var infoWindowContent = [
    ['<div class="info_content">' +
    '<h3>London Eye</h3>' +
    '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' +        '</div>'],
    ['<div class="info_content">' +
    '<h3>Palace of Westminster</h3>' +
    '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
    '</div>']
];
    
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map  
for( i = 0; i < markers.length; i++ ) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
        position: position,
        map: map,
        title: markers[i][0]
    });
    
    // Allow each marker to have an info window    
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.open(map, marker);
        }
    })(marker, i));

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
    this.setZoom(14);
    google.maps.event.removeListener(boundsListener);
});

}

@juliettech13
Copy link

juliettech13 commented Jul 25, 2018

Where did you pass the API key if you were using this script?
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

rather than the one suggested in the Google Maps API page(https://developers.google.com/maps/documentation/javascript/get-api-key#get-an-api-key)?

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script>

@khadkaPratik
Copy link

@juliettech13 Please Generate API key and just add it to this script below

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

@egajavier
Copy link

love you bro

@datvit
Copy link

datvit commented Sep 24, 2018

thx u bro u are fucking awesome

Copy link

ghost commented Oct 24, 2018

Good example, how to make infobox opened by default for all markers ?

@snehamin
Copy link

snehamin commented Mar 6, 2019

Thanks

@ali-syria
Copy link

Thanks

@piratheep4
Copy link

thank you very much bro .
this cord to easy and very usedfull

@aadityagoel
Copy link

thank you so much for code and it working fine and show all the location are visible.
but on the map it shows "For development purpose only".

@parth1020
Copy link
Author

thank you so much for code and it working fine and show all the location are visible.
but on the map it shows "For development purpose only".

Hello Aaditya

you need to replace below link.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script>

for the your api key ,
go to https://developers.google.com/maps/documentation/javascript/get-api-key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment