0

I have been working with the Google Maps API v3 to create a centre locator as explained in this tutorial https://developers.google.com/maps/articles/phpsqlsearch_v3.

I have edited it to my own needs and have a table below the map with the details of the local stores. This works in Chrome, Firefox and IE8 however I cannot get it to work in IE7. i am not getting any errors just the results table will not show at all, anyone have any ideas?. I have used IE javascript debug tools and the data seems to be coming through ok

Here is the JS

$(document).ready(function () {

$('form').after('<div id="map"></div>');
$('#map').after('<div id="directionsPanel"></div>');
$('#directionsPanel').after('<h3 id="local-centres">Your search results</h3>');
$('h3#local-centres').hide();
$('h3#local-centres').after('<table id="locationSelect"></table>');
var tableHeaders = '<ul class="col-titles"><li class="centre-title">Centre</li><li class="address-title">Address &amp Tel</li><li class="distance-title">Distance</li><li class="option-title">Options</li></ul>'

$('#directionsPanel').hide();
$('#directionsPanel').prepend('<h2>Directions by text - Driving</h2>');
$('#directionsPanel').before('<a href="#" class="print-locations" id="print-locations">Print text directions</a>');
$('a.print-locations').hide();


function runFunctionIfEnter(e, fnName) { // the arguments here are the event (needed to detect which key is pressed), and the name of the resulting function to run if Enter has been pressed.
    var keynum; // establish variable to contain the value of the key that was pressed
    // now, set that variable equal to the key that was pressed
    if (window.event) // ID
    {
        keynum = e.keyCode;
    } else if (e.which) // other browsers
    {
        keynum = e.which;
    }
    if (keynum == 13) { // if the key that was pressed was Enter (ascii code 13)
        eval(fnName)(); // run the resulting function name that was specified as an argument
    }
}



$('#showmarkers').click(function () {
    searchLocations();

});
$('input#addressInput').keypress(function (e) {
    if (e.keyCode == 13) {
        searchLocations();
        return false;
    }
});
$('#radiusSelect').change(function () {
    searchLocations();
});
$('a.print-locations').click(function () {
    printIt(document.getElementById('directionsPanel').innerHTML);
    return false;
});

$('input#reset-markers').click(function () {
    clearLocations();
    $('ul.col-titles').remove();
    allLocations();
});


var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var markers = [];
var locationSelect;
var geocoder;
var userMarker;
var win = null;

// $('table#locationSelect').prepend('<tr><th>Centre</th><th>Address &amp; Tel</th><th>Distance</th><th>Options</th></tr>');

function printIt(printDirection) {

    win = window.open();
    self.focus();
    win.document.open();
    win.document.write('<' + 'html' + '><' + 'head' + '><' + 'style' + '>');
    win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
    win.document.write('<' + '/' + 'style' + '><' + '/' + 'head' + '><' + 'body' +   '>');
    win.document.write(printDirection);
    win.document.write('<' + '/' + 'body' + '><' + '/' + 'html' + '>');
    win.document.close();
    win.print();
    win.close();
}

// initialise the map 
function load() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(53, -1.7),
        zoom: 6,
        mapTypeId: 'roadmap',
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        }
    });


    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    infoWindow = new google.maps.InfoWindow();
    locationSelect = document.getElementById("locationSelect");
allLocations();
}

load();

function allLocations() {

    var searchUrl = 'search_all_genxml.php';
    downloadUrl(searchUrl, function (data) {
        var xml = parseXml(data);
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        var bounds = new google.maps.LatLngBounds();
        //loop through all markers returned and save in variables
        if (markerNodes.length < 1) {
            $('h3#local-centres').hide();
            var noCentres = "Sorry we have no centres in this distance range. Please try expanding your search";
            alert(noCentres);
            _gaq.push(['_trackEvent', 'search', 'click', 'search_none-location']);

        } else {

            for (var i = 0; i < markerNodes.length; i++) {
                var name = markerNodes[i].getAttribute("name");
                var address = markerNodes[i].getAttribute("address");
                var postcode = markerNodes[i].getAttribute("postcode");
                var telephone = markerNodes[i].getAttribute("telephone");
                var email = markerNodes[i].getAttribute("email");
                var page = markerNodes[i].getAttribute("page");
                var distance = parseFloat(markerNodes[i].getAttribute("distance"));
                var latlng = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")), parseFloat(markerNodes[i].getAttribute("lng")));
                // call createOption and createMarker functions
                //createOption(name, address, postcode, telephone, email, page, distance, i);
                //alert(name);
                createMarker(latlng, name, address, postcode, telephone, email, page);
                bounds.extend(latlng);
            }
            // Don't zoom in too far on only one marker
            if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
                var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
                var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - 0.01, bounds.getNorthEast().lng() - 0.01);
                bounds.extend(extendPoint1);
                bounds.extend(extendPoint2);
            }

        }
        map.fitBounds(bounds);
        //locationSelect.style.visibility = "visible";
        var localCentres = document.getElementById('local-centres');
        //localCentres.style.visibility = "visible";
        locationSelect.onchange = function () {
            var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
            google.maps.event.trigger(markers[markerNum], 'click');
        };
    });



}

// Geocode the users address and pass result to searchLocationsNear function
function searchLocations() {
    //console.log('hello');
    var address = document.getElementById("addressInput").value;
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        address: address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            searchLocationsNear(results[0].geometry.location);
            map.setCenter(results[0].geometry.location);
            userMarker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            var htmlContent = "<div>" + "<h3>" + "Your Address" + "</h3>" + "<p>" + address + "</p>" + "</div>";
            var infowindow = new google.maps.InfoWindow({
                content: htmlContent
            });
            google.maps.event.addListener(userMarker, 'click', function () {
                infowindow.open(map, userMarker);
            });

            if($('ul.col-titles').length > 0){

            } else {
                $('table#locationSelect').before(tableHeaders);
                console.log(locationSelect);
            }


        } else if (address === '') {
            clearLocations();
            allLocations();
            _gaq.push(['_trackEvent', 'search', 'click', 'search_none-location']);
        } else {
            alert(address + ' not found');
            _gaq.push(['_trackEvent', 'search', 'click', 'search_none-location']);
        }
    });
}

// Clear all locations on map after 
function clearLocations() {
    directionsDisplay.setMap(null);
    if (userMarker) {
        userMarker.setMap(null);
    }
    infoWindow.close();
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers.length = 0;

    //var children = document.getElementById('locationSelect').childNodes;
    //locationSelect.innerHTML = "";
    $('#locationSelect tr').remove();
    $('#directionsPanel').slideUp('slow');
    $('a.print-locations').hide();
    $('h3#local-centres').hide();
}

// call clearLocations and loop through all results
function searchLocationsNear(center) {
    clearLocations();

    var radius = document.getElementById('radiusSelect').value;
    var searchUrl = 'search_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
    downloadUrl(searchUrl, function (data) {
        var xml = parseXml(data);
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        var bounds = new google.maps.LatLngBounds();
        //loop through all markers returned and save in variables
        if (markerNodes.length < 1) {

            var noCentres = "Sorry we have no centres in this distance range. Please try expanding your search";
            alert(noCentres);
            _gaq.push(['_trackEvent', 'search', 'click', 'search_none-location']);

        } else {

            for (var i = 0; i < markerNodes.length; i++) {
                var name = markerNodes[i].getAttribute("name");
                var address = markerNodes[i].getAttribute("address");
                var postcode = markerNodes[i].getAttribute("postcode");
                var telephone = markerNodes[i].getAttribute("telephone");
                var email = markerNodes[i].getAttribute("email");
                var page = markerNodes[i].getAttribute("page");
                var distance = parseFloat(markerNodes[i].getAttribute("distance"));
                var latlng = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")), parseFloat(markerNodes[i].getAttribute("lng")));
                // call createOption and createMarker functions
                console.log(locationSelect);
                createOption(name, address, postcode, telephone, email, page, distance, i);

                createMarker(latlng, name, address, postcode, telephone, email, page);
                bounds.extend(latlng);
            }
            $('h3#local-centres').show();
            // Don't zoom in too far on only one marker
            if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
                var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
                var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - 0.01, bounds.getNorthEast().lng() - 0.01);
                bounds.extend(extendPoint1);
                bounds.extend(extendPoint2);
            }

        }
        map.fitBounds(bounds);
        locationSelect.style.visibility = "visible";
        var localCentres = document.getElementById('local-centres');
        localCentres.style.visibility = "visible";
        locationSelect.onchange = function () {
            var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
            google.maps.event.trigger(markers[markerNum], 'click');
        };
    });
}

//create a custom marker
function createMarker(latlng, name, address, postcode, telephone, email, page) {

    var img = new google.maps.MarkerImage('kaplan-logo.png', new google.maps.Size(20, 50), new google.maps.Point(0, 0), new google.maps.Point(10, 40));
    var shape = {
        coord: [1, 1, 1, 20, 18, 20, 18, 1],
        type: 'poly'
    };
    var html = "<div class='center-info'>" + "<h2>" + name + "</h2>" + "<p>" + address + "</p>" + "<p class='postcode'>" + postcode + "</p>" + "<p>Tel: " + telephone + "</p>" + "<a href=mailto:" + email + ">" + email + "</a>" + "<a href=" + page + " target='_blank'>" + "View centre page" + "</a>" + "</div>";
    var infowindow = new google.maps.InfoWindow({
        content: html
    });
    var marker = new google.maps.Marker({
        map: map,
        icon: img,
        shape: shape,
        animation: google.maps.Animation.DROP,
        position: latlng
    });

    markers.push(marker);
    //alert(markers);
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });
}

// create text lists of address nearby
function createOption(name, address, postcode, telephone, email, page, distance, i) {
    i = i + 1;
    var rowOption = document.createElement("tr");
    rowOption.className = 'local-centre';
    var titleOption = document.createElement("td");
    titleOption.className = 'centre-name';
    var titleLink = document.createElement("a");
    titleLink.setAttribute('href', page);
    titleLink.innerHTML = "<h3>" + name + "</h3>";
    var addressOption = document.createElement("td");
    addressOption.className = 'address';
    addressOption.innerHTML = "<p>" + address + "</p>" + "<p class='postcode" + i + "'>" + postcode + "</p>" + "<p> Tel: " + telephone + "</p>";
    var distanceOption = document.createElement("td");
    distanceOption.className = 'distance';
    distanceOption.innerHTML = "<p class='distance'>" + distance.toFixed(1) + " miles" + "</p>";
    var directionsOption = document.createElement("td");
    directionsOption.className = "directions";
    directionsOption.innerHTML = "<button class='direction-btn directionSubmit" + i + "' type='button'>Get Directions</button>";
    var pageUrl = document.createElement("a");
    pageUrl.className = 'centre-url';
    pageUrl.innerHTML = "View centre page >";
    pageUrl.setAttribute('href', page);
    pageUrl.setAttribute('target', '_blank');
    directionsOption.appendChild(pageUrl);
    locationSelect.appendChild(rowOption);
    console.log(rowOption);
    rowOption.appendChild(titleOption);
    titleOption.appendChild(titleLink);
    rowOption.appendChild(addressOption);
    rowOption.appendChild(distanceOption);
    rowOption.appendChild(directionsOption);
    $('tr:odd').addClass("odd");
    $('tr:even').addClass("even");
    //divOptionContent.appendChild(directionsDiv);
    $('.directionSubmit' + i).click(function () {
        var caddress = $('.postcode' + i).text();
        var address = $('#addressInput').val();
        calcRoute(address, caddress);
        $('#directionsPanel').slideDown('slow', function () {
            $('a.print-locations').show();

        });
        $('html, body').animate({
            scrollTop: 0
        }, 'slow');

    });
}



// calculate the route from users address to centre
function calcRoute(address, caddress) {
    var request = {
        origin: address,
        destination: caddress,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL
    };
    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
            directionsDisplay.setMap(map);
        }
    });

} // end of calcRoute function


function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');
  }
}

function doNothing() {}


}); // end of jquery 

Here is the HTML

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js lt-ie9 lt-ie8 ie7" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!-- Consider adding a manifest.appcache: h5bp.com/d/Offline -->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>

<meta charset="UTF-8" />
<title>Centre Search</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="_assets/css/style.css" media="screen" />
<link rel="stylesheet" href="_assets/css/print.css" media="print" />

</head>
<body>


<div id="centre-map">
<h2>Centre Locations</h2>

<p>The map below allows you find your nearest Centre, get directions and contact the relevant team.</p>


    <form>
        <label>Your City / Postcode:</label>
        <input type="text" id="addressInput" />
        <label>Radius:</label>
        <select id="radiusSelect" onchange="_gaq.push(['_trackEvent', 'search', 'click', 'search_select_location']);">
            <option value="5">5 Miles</option>
            <option value="10">10 Miles</option>
            <option value="25" selected>25 Miles</option>
            <option value="50">50 Miles</option>
            <option value="75">75 Miles</option>
        </select>
        <input type="button" value="Search" id="showmarkers" />
        <input type="reset" value="Reset" id="reset-markers" />
    </form>


</div>




<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCDgCnbWSMQhBBmLnIOBKGn1EznhPVcVoY&sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="_assets/js/script.js?v=<?=filemtime('_assets/js/script.js');?>"></script>

</body>
</html>
Kelly
  • 3,709
  • 4
  • 20
  • 31
James
  • 39
  • 1
  • 10

1 Answers1

0

console.log() will cause problems in IE7, take out or comment out all of your console statements and try it again. Not much of an answer, I'm at work and just stabbing at this, is that totally ag'in' the rules? I'm pretty sure if the rest of your code is functional removing console.log() statements throughout will fix it in IE 7.

Read this: Testing for console.log statements in IE

Community
  • 1
  • 1
Jeremy Anderson
  • 826
  • 5
  • 16