Solved

Placing my location and multiple markers on a google map

Posted on 2015-01-30
5
1,012 Views
Last Modified: 2015-01-31
I am really struggling here and hope you can help. I have been hacking together disparate pieces of code and can make one part work but only by breaking the next so am hopeful someone can help me pull of this together:

I found this code to place multiple markers on the page:

      
      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: navigator.geolocation.getCurrentPosition(showPosition, showError),
      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));
    }

Open in new window


So i hoped that by replacing the locations array with:
var Locations = [{% block content %}{% for e in object_list %}['{{ e.name}}', {{ e.latitude}}, {{ e.longitude}}, 4],
        {% endfor %}]{% endblock %};

Open in new window

would mean that I could grab my locations and other attributes from my database. The output looks the same:

var Locations = [['Everyone Active Hartham Leisure Centre', 51.800052, -0.077467, 4],
        ['Gordons Gym', 51.480226, 0.069589, 4],
        ['The Concorde Club', 51.48808, -0.40301, 4],
        ['Croydon High Sports Club', 51.341246, -0.061708, 4],
        ['Everyone Active Northolt Leisure Centre', 51.548934, -0.375026, 4],
        ['Everyone Active Central Park Leisure Centre', 51.602689, 0.228719, 4],
        ['Heston Community Sports Hall', 51.480955, -0.365949, 4],
        ['Everyone Active Westminster Lodge Leisure Centre', 51.750365, -0.34032, 4],
        ['Everyone Active Hornchurch Sports Centre', 51.563842, 0.207556, 4],
...
...
...
        ['The Landmark Spa and Health Club', 51.521554, -0.161116, 4],
        ['Brands Hatch Place Hotel and Spa', 51.361902, 0.269406, 4],
        ];

Open in new window

NB I didn't know what the final variable was for, so I just put "4" there but insight into what that should be would also be helpful. I also notice a trailing comma but can't work out how to remove that, and hence can't see if that is the problem.

Where have I gone wrong?
thanks
0
Comment
Question by:lz7cjc
  • 3
  • 2
5 Comments
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40581132
I see a couple of issues here that are easily remedied but I'm concentrating just on the JavaScript, not able to make/test changes to the Python/Django(?) part.

1) var Locations

JavaScript is case sensitive so if you want to use a capital L, you need to change the rest of the code as well, otherwise leave it lowercase.

2) The ", 4" at the end of each array entry

that's not used in the code you've posted (may have been used in the infowindow.setContent call originally) so unless you have more code where at some point locations[x][3] is used, it's not relevant here and you should be able to leave it out altogether.

3) trailing comma

this has actually been changed at some point in the definition of the language to be allowed (and ignored) so it won't affect the length of your array and shouldn't be a problem if you're targeting modern browsers.

If you do need to support old browsers (like IE8) there are at least 2 solutions:

(a) change the location of the comma from the end to the start of the line, leaving an empty entry at the start of the array which you can skip by making the for loop start at i = 1.
    for (i = 1; i < locations.length; i++) {
      // ...
    }

Open in new window


(b) test for empty entries in the for loop:
    for (i = 0; i < locations.length; i++) {
      var x = i; // don't actually use this code, just use "i" below, but you can't put an "i" in square brackets in a comment on EE :-)
      if (locations[x] != null) { // in case trailing comma is not ignored
        // ...
      }
    }

Open in new window


((c)) the best solution would be some sort of {% if ... %} but I don't know the syntax for that...
0
 

Author Comment

by:lz7cjc
ID: 40581317
thanks Robert that's fantastic, really helpful. Unfortunately I can't implement since I appear to have now taken a massive step back and can't get the map to even appear. Can you help me?
<!DOCTYPE html>
<html>
    <head>
        <script src="http://maps.google.com/maps/api/js?sensor=true">
        </script>
        <script>


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: navigator.geolocation.getCurrentPosition(showPosition, showError),
      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>
            </head>
    <style>

    #map {
        height: 400px;
        width: 700px;
        }

    </style>
    <body>
        <div>
        <h2>HTML5 Show Location on GoogleMap Sample</h2>

            <div id="map"></div>
        </div>

    </body>
</html>

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40581323
The script block with your code needs to be able to reference the html document because of this line:
document.getElementById('map')

Open in new window

So you have 2 options: either wrap your code in a function and run it on window.onload, or move the whole script block to the end of the document (just before </body>).

Then, check if it works for you. In my browser the console (using F12) shows an error on the geolocation call. To test, I replaced it with:
center: new google.maps.LatLng(locations[0][1], locations[0][2]),

Open in new window

0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
ID: 40581338
Working off some base code found on w3schools I got the following working: http://schutt.nl/ee/Q_28607042/
<!DOCTYPE html>
<html>
    <head>
      <meta charset="utf-8">
        <script src="http://maps.google.com/maps/api/js?sensor=true">
        </script>
            </head>
    <style>

    #map {
        height: 400px;
        width: 700px;
        }

    </style>
    <body>
        <div>
        <h2>HTML5 Show Location on GoogleMap Sample</h2>

            <div id="map"></div>
        </div>

        <script>


var locations = [['Everyone Active Hartham Leisure Centre', 51.800052, -0.077467],
        ['Gordons Gym', 51.480226, 0.069589],
        ['The Concorde Club', 51.48808, -0.40301],
        ['Croydon High Sports Club', 51.341246, -0.061708],
        ['Everyone Active Northolt Leisure Centre', 51.548934, -0.375026],
        ['Everyone Active Central Park Leisure Centre', 51.602689, 0.228719],
        ['Heston Community Sports Hall', 51.480955, -0.365949],
        ['Everyone Active Westminster Lodge Leisure Centre', 51.750365, -0.34032],
        ['Everyone Active Hornchurch Sports Centre', 51.563842, 0.207556],
//...
        ['The Landmark Spa and Health Club', 51.521554, -0.161116],
        ['Brands Hatch Place Hotel and Spa', 51.361902, 0.269406],
        ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    navigator.geolocation && navigator.geolocation.getCurrentPosition(showPosition, showError) == undefined && showError();

    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));
    }

function showPosition(position) {
  lat = position.coords.latitude;
  lon = position.coords.longitude;
  latlon = new google.maps.LatLng(lat, lon);
  map.setCenter(latlon);
}

function showError(error) {
  map.setCenter(new google.maps.LatLng(locations[0][1], locations[0][2])); // default 1st from array
}

</script>
    </body>
</html>

Open in new window

If the geolocation doesn't work, it takes the first location in the array as center.
0
 

Author Comment

by:lz7cjc
ID: 40581481
thank you so much for your help - you have just saved me many headaches!
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now