JavaScript: Google Maps API

From The Travis van der Font Wiki
Jump to: navigation, search

Simple Single Location by address (using iFrame)

<iframe
  class       = "gmap"
  frameborder = "0"
  src         = "https://www.google.com/maps/embed/v1/place?key=XXXXXXYYYYYZZZZZ&q=123%2C+Street+L-1234+Luxembourg"
>
</iframe>

Typical Single Location with Marker

<script async defer src="https://maps.googleapis.com/maps/api/js?key=XYXYXYXYXYX&callback=initMap">
</script>
<script>
function initMap()
{
    var map = new google.maps.Map(document.getElementById('gmap'),
    {
        center: new google.maps.LatLng(-33.863276, 151.207977),
        zoom: 12,
    });

    var marker = new google.maps.Marker(
    {
        map: map,
        position: new google.maps.LatLng(
            parseFloat(-33.863276),
            parseFloat(151.207977)),
    });

    marker.addListener('click', function ()
    {
        new google.maps.InfoWindow({
            content: '<div>Test data 2</div>',
        }).open(map, marker);
    });
}
</script>

Dynamic Markers (from an array)

AJAXrequest('/api/locations', JSON.stringify(request), function (data)
{
    var marker;
    var center     = {lat: gmap.dataset.locationLat, long: gmap.dataset.locationLong};
    var infowindow = new google.maps.InfoWindow;
    var map        = new google.maps.Map(document.getElementById('map-canvas'),
    {
        zoom: 10,
        center: new google.maps.LatLng(center.lat, center.long),
        //mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    for (var key in data)
    {
        if (data.hasOwnProperty(key))
        {
            var cordinates = data[key].split(',');

            marker = new google.maps.Marker(
            {
                position: new google.maps.LatLng(parseFloat(cordinates[0]), parseFloat(cordinates[1])),
                map: map,
            });

            google.maps.event.addListener(marker, 'click', (function (marker, key)
            {
                return function ()
                {
                    AJAXrequest('/api/data', JSON.stringify({'id': key}), function (data)
                    {
                        infowindow.setContent('<div><strong>'+data.name+'</strong> ('+key+')</div>');
                        infowindow.open(map, marker);
                    });
                };
            })(marker, key));
        }
    }
});

Street View