1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Have trouble getting google maps to load on page

Discussion in 'JavaScript' started by kwood30, Mar 16, 2016.

  1. #1
    Please see my code below, I have sorted out all my coding to work how I want it too, but for some reason I just can't get it to load the map when you open it up in a browser. Can anyone see where I have gone wrong and guide me to get it work please. Thank you.

    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <title>County Polygons + Markers w/elapsed time</title>
    <script src="../fiveenglishcounties.js" charset="UTF-8">
    // positioning codes © Copyright 2012 UK Data Service. All rights reserved Creative Commons License https://www.ukdataservice.ac.uk
    </script>
    <script type="text/javascript">
    var map, bounds, geocoder, markers = [], pollies, pinImage, pinColor = '00FF00', defaultPinColor = 'F75850', defaultPin;
    $('#controls input[name="[counties]"]').click(function(){
    var poly = pollies[this.value];
    if(poly.map){
    poly.infowindow.close();
    poly.setMap(null);
    this.checked = false;
    } else {
    poly.setMap(map);
    this.checked = true;
    }
    });
    
    function elapsed(rfd) {
    var rs = (new Date().getTime() - rfd.getTime()) / 1000,
    days = Math.floor(rs / 86400),
    hours = Math.floor((rs - (days * 86400 )) / 3600),
    minutes = Math.floor((rs - (days * 86400 ) - (hours * 3600 )) / 60),
    secs = Math.floor((rs - (days * 86400 ) - (hours * 3600 ) - (minutes * 60))),
    fet = secs + 's';
    if(minutes){fet = minutes + 'm' + ' ' + fet;}
    if(hours){fet = hours + 'h' + ' ' + fet;}
    if(days){fet = days + ' Day' + (days > 1? 's' : '') + ' ' + fet;}
    return 'Created: ' + rfd.toLocaleTimeString().toLowerCase() + ',<br>' + fet + ' ago';
    }
    function createMarker(latlng, html, map) {
    var ref = $.trim($('#reference').val()),
    infowindow = new google.maps.InfoWindow({
    content: ref || html
    }),
    marker = new google.maps.Marker({
    map: map,
    time : new Date(),
    position: latlng,
    html: html,
    icon: defaultPin,
    infowindow: infowindow
    }),
    $tm = $('#themarkers').append('<option value="' + html + '" title="' + infowindow.content + '">' + html + '</option>');
    $tm.get(0).selectedIndex = 0;
    marker.addListener('mouseover', function() {
    clearInterval(infowindow.timer);
    infowindow.setContent((ref || html) + '<br>' + elapsed(marker.time));
    $('#supplementwindow').html(infowindow.content).fadeIn();
    infowindow.timer = setInterval(function(){
    infowindow.setContent((ref || html) + '<br>' + elapsed(marker.time));
    $('#supplementwindow').html(infowindow.content);
    }, 300);
    infowindow.open(map, this);
    });
    marker.addListener('mouseout', function() {
    clearInterval(infowindow.timer);
    infowindow.close();
    $('#supplementwindow').fadeOut();
    });
    marker.addListener('click', function() {
    var oe = this.optel;
    $tm.get(0).selectedIndex = $('option', $tm).index(oe);
    $tm.trigger('change');
    });
    marker.optel = $('option', $tm).last();
    $tm.get(0).size = $('option', $tm).length;
    markers.push(marker);
    }
    $('#formcont form').submit(function(e){
    var addresses = $('.address', this);
    addresses = [addresses.eq(0).val(), addresses.eq(1).val()];
    addresses.forEach(function(address, refnum) {
    if (address) {
    geocoder.geocode({
    'address': address
    }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    createMarker(results[0].geometry.location, address, map, refnum);
    bounds.extend(results[0].geometry.location);
    map.fitBounds(bounds);
    } else {
    alert("Geocode was not successful for the following reason: " + status);
    }
    });
    }
    });
    e.preventDefault();
    });
    $('#activatemarker').click(function(){
    var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
    if(!i){return;}
    $.each(markers, function(idx, v){
    if(v.html === i){
    v.setIcon(pinImage);
    return false;
    }
    });
    });
    $('#removemarker').click(function(){
    var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
    if(!i){return;}
    $.each(markers, function(idx, v){
    if(v.html === i){
    v.setMap(null);
    markers.splice(idx, 1);
    return false; }
    });
    $o.remove();
    bounds = new google.maps.LatLngBounds();
    if(markers.length){
    $.each(markers, function(i, v){
    bounds.extend(v.position);
    });
    map.fitBounds(bounds);
    }
    if(markers.length < 2){
    map.setZoom(markers.length? 13 : 8);
    }
    tm.get(0).size = $('option', tm).length;
    });
    $('#themarkers').change(function(){
    this.title = this.options[this.options.selectedIndex].title;
    var i = this.value;
    if(!i){return;}
    $.each(markers, function(idx, v){
    if(v.html === i){
    map.setCenter(v.position);
    map.setZoom(10);
    return false;
    }
    });
    this.size = $('option', $(this)).length;
    });
    $('#showall').click(function(){
    $('#themarkers').get(0).selectedIndex = 0;
    if(!markers.length){
    map.setCenter(new google.maps.LatLng(52.178227, -0.46013));
    map.setZoom(8);
    return;
    }
    map.fitBounds(bounds);
    if(markers.length === 1){
    map.setZoom(8);
    }
    });
    function formatCodes(codeString){
    var a = codeString.split(' '), l = a.length, po;
    while(--l > -1){
    po = a[l].split(',');
    a[l] = {lat: +po[1], lng: +po[0]};
    }
    return a;}
    function initMap() {
    pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor);
    defaultPin = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + defaultPinColor);
    var p;
    geocoder = new google.maps.Geocoder();
    bounds = new google.maps.LatLngBounds();
    map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {lat: 52.178227, lng: -0.4013},
    mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    pollies = {
    Bedfordshire: {
    paths: BedfordshireCodes,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.15,
    latlng: {lat: 52.002974, lng: -0.465139}
    },
    Bedford: {
    paths: BedfordCodes,
    strokeColor: '#FFC0CB',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FFC0CB',
    fillOpacity: 0.15,
    latlng: {lat: 52.135973, lng: -0.466655}
    },
    Hertfordshire: {
    paths: HertfordshireCodes,
    strokeColor: '#FFFF55',
    strokeOpacity: 0.9,
    strokeWeight: 2,
    fillColor: '#FFFF55',
    fillOpacity: 0.25,
    latlng: {lat: 51.809782, lng: -0.237674}
    },
    Cambridgeshire: {
    paths: CambridgeshireCodes,
    strokeColor: '#00FF00',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#00FF00',
    fillOpacity: 0.15,
    latlng: {lat: 52.305297, lng: 0.021820}
    },
    Northamptonshire: {
    paths: NorthamptonshireCodes,
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0000FF',
    fillOpacity: 0.15,
    latlng: {lat: 52.272994, lng: -0.875552}
    }
    };
    for(p in pollies){
    var polly = pollies[p];
    polly.paths = formatCodes(polly.paths);
    polly = pollies[p] = new google.maps.Polygon(polly);
    polly.infowindow = new google.maps.InfoWindow({
    content: p,
    position: polly.latlng
    });
    polly.addListener('click', function(){
    if(this.infowindow.map){
    this.infowindow.close();
    } else {
    this.infowindow.open(map, this);
    }
    });
    polly.setMap(map); }
    
    }
    function initialize() {
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    </head>
    
    <body>
    
    <div style="width:300px; height: 500px; float:right; padding-left:10px; padding-right:10px; margin: 50px 90px 50px 75px">
    <h1 align="center">Map Search</h1>
    
    <div id="formcont" style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" align="center" >
    
    <form>
    <br>
    Location 1 <input type="text" class="address">
    <br>
    <br>
    Location 2
    <input type="text" class="address">
    <br>
    <br>
    Reference
    <input type="text" id="reference">
    <br>
    <br>
    <input type="submit" value="Submit">
    </form>
    
    
    </div>
    
    <div style="position: absolute; right: 170px; top: 365px; border: 1px solid #bbb; padding: 5px;
    border-radius: 12px;">
    <label>Bedford: <input type="checkbox" checked name="[counties]" value="Bedford"> (pink)</label><br>
    <label>Bedfordshire: <input type="checkbox" checked name="[counties]" value="Bedfordshire"> (red)</label><br>
    <label>Hertfordshire: <input type="checkbox" checked name="[counties]" value="Hertfordshire"> (yellow)</label><br>
    <label>Cambridgeshire: <input type="checkbox" checked name="[counties]" value="Cambridgeshire"> (green)</label><br>
    <label>Northamptonshire: <input type="checkbox" checked name="[counties]" value="Northamptonshire"> (blue)</label>
    </div>
    
    <div id="dropsandbuttons" style="position: absolute; right: 200px; top: 500px; border: 1px solid #bbb; padding: 5px;
    border-radius: 12px;"><select id="themarkers"><option value="">Select Marker</option>
    </select><br>
    <input type="button" id="showall" title="Or Reset if None" value="Show All Markers"><br>
    <input type="button" id="removemarker" title="Remove Selected Marker" value="Remove Marker"><br>
    <input type="button" id="activatemarker" title="Activate Selected Marker" value="Activate Marker">
    </div>
    </div>
    <div id="map"></div>
    
    <div id="supplementwindow" style="border:1px solid #ccc; background:#e5e5e5; align-content:center; float:left; clear: both position:absolute; margin:200px 0px 200px 200px; padding: 5px; border-radius: 12px;" ></div>
    
    
    
    </body>
    </html>
    
    Code (markup):
     
    kwood30, Mar 16, 2016 IP
  2. Blizzardofozz

    Blizzardofozz Well-Known Member

    Messages:
    132
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    118
    #2
    I've not revised all code but your map had not loaded because you use paths you've not defined so I comment them out. Also you are not calling initMap(). Here: polly = pollies[p] = new google.maps.Polygon(polly.latlng.lat, polly.latlng.lng); use polly latling you already have, no need for paths. no need for formatCodes function. Also give height and width of the div with id of map.

    I don't know why you need 2 initialization functions.

    I partially fixed the code. The map is loading.

    
    <div id="map" style="width: 500px; height: 500px"></div>
    
    Code (markup):
     
    var map, bounds, geocoder, markers = [], pollies, pinImage, pinColor = '00FF00', defaultPinColor = 'F75850', defaultPin;
    
    $('#controls input[name="[counties]"]').click(function () {
        'use strict';
        var poly = pollies[this.value];
        if (poly.map) {
            poly.infowindow.close();
            poly.setMap(null);
            this.checked = false;
        } else {
            poly.setMap(map);
            this.checked = true;
        }
    });
    
    function elapsed(rfd) {
        'use strict';
        var rs = (new Date().getTime() - rfd.getTime()) / 1000,
            days = Math.floor(rs / 86400),
            hours = Math.floor((rs - (days * 86400)) / 3600),
            minutes = Math.floor((rs - (days * 86400) - (hours * 3600)) / 60),
            secs = Math.floor((rs - (days * 86400) - (hours * 3600) - (minutes * 60))),
            fet = secs + 's';
        if (minutes) { fet = minutes + 'm' + ' ' + fet; }
        if (hours) { fet = hours + 'h' + ' ' + fet; }
        if (days) { fet = days + ' Day' + (days > 1 ? 's' : '') + ' ' + fet; }
        return 'Created: ' + rfd.toLocaleTimeString().toLowerCase() + ',<br>' + fet + ' ago';
    }
    
    function createMarker(latlng, html, map) {
        'use strict';
        var ref = $.trim($('#reference').val()),
            infowindow = new google.maps.InfoWindow({
                content: ref || html
            }),
            marker = new google.maps.Marker({
                map: map,
                time : new Date(),
                position: latlng,
                html: html,
                icon: defaultPin,
                infowindow: infowindow
            }),
            $tm = $('#themarkers').append('<option value="' + html + '" title="' + infowindow.content + '">' + html + '</option>');
        
        $tm.get(0).selectedIndex = 0;
        marker.addListener('mouseover', function () {
            clearInterval(infowindow.timer);
            infowindow.setContent((ref || html) + '<br>' + elapsed(marker.time));
            $('#supplementwindow').html(infowindow.content).fadeIn();
            infowindow.timer = setInterval(function () {
                infowindow.setContent((ref || html) + '<br>' + elapsed(marker.time));
                $('#supplementwindow').html(infowindow.content);
            }, 300);
            infowindow.open(map, this);
        });
        marker.addListener('mouseout', function () {
            clearInterval(infowindow.timer);
            infowindow.close();
            $('#supplementwindow').fadeOut();
        });
        marker.addListener('click', function () {
            var oe = this.optel;
            $tm.get(0).selectedIndex = $('option', $tm).index(oe);
            $tm.trigger('change');
        });
        marker.optel = $('option', $tm).last();
        $tm.get(0).size = $('option', $tm).length;
        markers.push(marker);
    }
    
    $('#formcont form').submit(function (e) {
        'use strict';
        var addresses = $('.address', this);
        addresses = [addresses.eq(0).val(), addresses.eq(1).val()];
        addresses.forEach(function (address, refnum) {
            if (address) {
                geocoder.geocode({
                    'address': address
                }, function (results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        createMarker(results[0].geometry.location, address, map, refnum);
                        bounds.extend(results[0].geometry.location);
                        map.fitBounds(bounds);
                    } else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });
            }
        });
        e.preventDefault();
    });
    $('#activatemarker').click(function () {
        'use strict';
        var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
        if (!i) { return; }
        $.each(markers, function (idx, v) {
            if (v.html === i) {
                v.setIcon(pinImage);
                return false;
            }
        });
    });
    
    $('#removemarker').click(function () {
        'use strict';
        var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
        if (!i) { return; }
        $.each(markers, function (idx, v) {
            if (v.html === i) {
                v.setMap(null);
                markers.splice(idx, 1);
                return false;
            }
        });
        $o.remove();
        bounds = new google.maps.LatLngBounds();
        if (markers.length) {
            $.each(markers, function (i, v) {
                bounds.extend(v.position);
            });
            map.fitBounds(bounds);
        }
        if (markers.length < 2) {
            map.setZoom(markers.length ? 13 : 8);
        }
        tm.get(0).size = $('option', tm).length;
    });
    $('#themarkers').change(function () {
        'use strict';
        this.title = this.options[this.options.selectedIndex].title;
        var i = this.value;
        if (!i) { return; }
        $.each(markers, function (idx, v) {
            if (v.html === i) {
                map.setCenter(v.position);
                map.setZoom(10);
                return false;
            }
        });
        this.size = $('option', $(this)).length;
    });
    $('#showall').click(function () {
        'use strict';
        $('#themarkers').get(0).selectedIndex = 0;
        if (!markers.length) {
            map.setCenter(new google.maps.LatLng(52.178227, -0.46013));
            map.setZoom(8);
            return;
        }
        map.fitBounds(bounds);
        if (markers.length === 1) {
            map.setZoom(8);
        }
    });
    //function formatCodes(codeString) {
    //    'use strict';
    //    var a = codeString.split(' '), l = a.length, po;
    //    while (--l > -1) {
    //        po = a[l].split(',');
    //        a[l] = {lat: +po[1], lng: +po[0]};
    //    }
    //    return a;
    //}
    function initMap() {
        'use strict';
        var p;
        pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor);
        defaultPin = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + defaultPinColor);
        geocoder = new google.maps.Geocoder();
        bounds = new google.maps.LatLngBounds();
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 8,
            center: {lat: 52.178227, lng: -0.4013},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        pollies = {
            Bedfordshire: {
    //            paths: BedfordshireCodes,
                strokeColor: '#FF0000',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#FF0000',
                fillOpacity: 0.15,
                latlng: {lat: 52.002974, lng: -0.465139}
            },
            Bedford: {
    //            paths: BedfordCodes,
                strokeColor: '#FFC0CB',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#FFC0CB',
                fillOpacity: 0.15,
                latlng: {lat: 52.135973, lng: -0.466655}
            },
            Hertfordshire: {
    //            paths: HertfordshireCodes,
                strokeColor: '#FFFF55',
                strokeOpacity: 0.9,
                strokeWeight: 2,
                fillColor: '#FFFF55',
                fillOpacity: 0.25,
                latlng: {lat: 51.809782, lng: -0.237674}
            },
            Cambridgeshire: {
    //            paths: CambridgeshireCodes,
                strokeColor: '#00FF00',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#00FF00',
                fillOpacity: 0.15,
                latlng: {lat: 52.305297, lng: 0.021820}
            },
            Northamptonshire: {
    //            paths: NorthamptonshireCodes,
                strokeColor: '#0000FF',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#0000FF',
                fillOpacity: 0.15,
                latlng: {lat: 52.272994, lng: -0.875552}
            }
        };
        for (p in pollies) {
            if (pollies.hasOwnProperty(p)) {
                var polly = pollies[p];
                //polly.latlng = formatCodes(polly.latlng);
                polly = pollies[p] = new google.maps.Polygon(polly.latlng.lat, polly.latlng.lng);
                polly.infowindow = new google.maps.InfoWindow({
                    content: p,
                    position: polly.latlng
                });
                polly.addListener('click', function () {
                    if (this.infowindow.map) {
                        this.infowindow.close();
                    } else {
                        this.infowindow.open(map, this);
                    }
                });
                polly.setMap(map);
            }
        }
    }
    
    function initialize() {
        'use strict';
        initMap();
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    Code (markup):
     
    Blizzardofozz, Mar 24, 2016 IP