Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts

    Google Maps API V3 - Generate Markers from JavaScript Array?

    I pulled this code from Google's example section to make markers on a v3 Google Maps API (I have added my own lat/long points and corresponding event listeners, of course, but this is still the spirit of the code):
    Code:
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
      var map;
      function initialize() {
        var map_center = new google.maps.LatLng(39.2,-84.479381);
        var store1 = new google.maps.LatLng(39.112456,-84.574779);
        var store2 = new google.maps.LatLng(39.314153,-84.261379);
        var store3 = new google.maps.LatLng(39.197099,-84.667579);
        var store4 = new google.maps.LatLng(39.16836,-84.479381);
        var myOptions = {
          zoom: 10,
          center: map_center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
        var marker1 = new google.maps.Marker({
            position: store1, 
            map: map, 
            title:"Store 1"
        });
        var marker2 = new google.maps.Marker({
            position: store2, 
            map: map, 
            title:"Store 2"
        });
        var marker3 = new google.maps.Marker({
            position: store3, 
            map: map, 
            title:"Store 3"
        });
        var marker4 = new google.maps.Marker({
            position: store4, 
            map: map, 
            title:"Store 4"
        });
        google.maps.event.addListener(marker1, 'click', function() {
          map.set_center(store1);
          map.set_zoom(16);
        });
        google.maps.event.addListener(marker2, 'click', function() {
          map.set_center(store2);
          map.set_zoom(16);
        });
        google.maps.event.addListener(marker3, 'click', function() {
          map.set_center(store3);
          map.set_zoom(16);
        });
        google.maps.event.addListener(marker4, 'click', function() {
          map.set_center(store4);
          map.set_zoom(16);
        });
      }
    </script>
    This works without fail, but when I try to use a javascript array to hold my values and loop my way through the marker creation like so:
    Code:
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
      var map;
      function initialize() {
        var map_center = new google.maps.LatLng(39.2,-84.479381);
        var store_locations = new Array();
        var temporary_stuff = new Array();
        store_locations[0] = "39.112456,-84.574779";
        store_locations[1] = "39.314153,-84.261379";
        store_locations[2] = "39.197099,-84.667579";
        store_locations[3] = "39.16836,-84.479381";
        var myOptions = {
          zoom: 10,
          center: map_center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        for(i=0;i<store_locations.length;i++){
            var marker_string = "position: "+new google.maps.LatLng(store_locations[i])+", map: map, title:\"Store "+(i+1)+"\";";
            temporary_stuff[i] = new google.maps.Marker(marker_string);
        }
        var markers = new Array();
        for(i=0;i<temporary_stuff.length;i++){
            var the_marker = "position: temporary_stuff[" + i + "], map: map, title:\"Store " + (i+1) + "\";";
            markers[i]= new google.maps.Marker(the_marker);
        }
      }
    </script>
    I get a blank map. Here's a link to the test file:
    http://rowsdower.freehostia.com/map_test.php

    It's not throwing up any errors in Firefox's developer or in IE but there it sits, a blank map.

    I'm sure this isn't clean or optimized code, but it looks correct to me. I've color-coded the code above to show what "for" loops are being used to try to replace which code. Hopefully that makes this more sensible.

    I haven't even tried to add the listeners yet since I can't get the markers to appear. Can anyone tell me why this isn't working or point me in a more productive direction?

    Is there a better way already out there that I haven't noticed?
    Last edited by Rowsdower!; 08-26-2009 at 03:35 PM. Reason: Problem Resolved...
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,449
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    You can't create a LatLng object from a *string*!!!

    You must create it from a PAIR of FLOATING POINT values!

    So several solutions. Perhaps the simplest:
    Code:
        store_locations = [ 
            new google.maps.LatLng(39.112456,-84.574779),
            new google.maps.LatLng(39.314153,-84.261379),
            new google.maps.LatLng(39.197099,-84.667579),
            new google.maps.LatLng(39.16836,-84.479381)
            ];
    ...
    Nor can you create a Marker from a string.

    Again, you must create it from the parameters.

    So toss out your strings and use parameters!

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,449
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    I have not yet used the version 3 api, but I think you want something like this:
    Code:
    <script type="text/javascript">
      var map;
      var markers = new Array();
      function initialize() {
        var map_center = new google.maps.LatLng(39.2,-84.479381);
        var store_locations = new Array();
        var temporary_stuff = new Array();
        store_locations = [ 
            new google.maps.LatLng(39.112456,-84.574779),
            new google.maps.LatLng(39.314153,-84.261379),
            new google.maps.LatLng(39.197099,-84.667579),
            new google.maps.LatLng(39.16836,-84.479381)
            ];
    
        var myOptions = {
          zoom: 10,
          center: map_center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        for(i=0;i<store_locations.length;i++)
        {
            markers[i] = new google.maps.Marker(
               { position: store_locations[i],
                 map: map,
                 title: "Store " + (i+1);
               } );
            google.maps.event.addListener(markers[i], 'click', 
                function() { map.set_center(store_locations[i]);
                             map.set_zoom(16);
                           } );
      }
    </script>
    I'm a bit nervous about using the [i] inside the map.set_center. I don't see how that function will know what the value of i is when it is invoked.

    I haven't used version 3 of the API.

    The way I coded it in V2, as translated to V3, would be something like this:

    Code:
            google.maps.event.addListener(markers[i], 'click', 
                function() { markerClick(this); }
                );
            ...
    
    And then a separate function:
    
    function markerClick( mark )
    {
        for ( var m = 0; m < markers.length; ++m )
        {
            if ( markers[m] == mark ) 
            {
                 map.set_center(store_locations[m]);
                 map.set_zoom(16);
                 return;
            }
        }
    }
    ...
    See how it works? I made that array of markers[] have page scope. Then, when one is clicked on, I search through the array to find which one was clicked on. And then *that* gives me the index into the array of locations.
    Last edited by Old Pedant; 08-25-2009 at 01:20 AM. Reason: Silly typos

  • Users who have thanked Old Pedant for this post:

    Rowsdower! (08-25-2009)

  • #4
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    OK, thanks for that run-down. Your code update to V3 worked just fine, FYI. Thanks much!

    If you don't mind humoring me I'm still a bit confused about why I can't make a string that holds the syntax for a new lat/long call and its parameters and pass that to new google.maps.Marker though. I assumed (incorrectly, it seems) that when I called new google.maps.Marker on var the_marker = "position: temporary_stuff[" + i + "], map: map, title:\"Store " + (i+1) + "\";"; that the function call and parameters held in temporary_stuff[i] as a string would be run in turn as though I has simply nested the function calls explicitly.

    In other words, I thought it would have the same effect as, say, this code here if we were on the first item in the array:
    Code:
    new google.maps.Marker(
      position: new google.maps.LatLng(
        position: 39.112456,-84.574779,
        map: map,
        title:"Store 1";
      );,
      map: map,
      title:"Store 1";
    );
    But now that I type all of that out it seems off anyway. Assuming I wasn't a total boob with the syntax above, why wouldn't this work as expected? Can you nest like this at all or was this what you were saying can't be done to begin with?

    Anyway, I probably won't be hosting that map test there for very long so for the sake of posterity here is the full code used in the working version for anyone who needs it:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    <head>
    <title>Google Maps API v3 Test...</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    //<![CDATA[
      var map;
      var markers = new Array();
      function initialize() {
        var map_center = new google.maps.LatLng(39.2,-84.479381);
        var store_locations = new Array();
        store_locations = [ 
            new google.maps.LatLng(39.112456,-84.574779),
            new google.maps.LatLng(39.314153,-84.261379),
            new google.maps.LatLng(39.197099,-84.667579),
            new google.maps.LatLng(39.16836,-84.479381)
            ];
        var myOptions = {
          zoom: 10,
          center: map_center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        for(i=0;i<store_locations.length;i++)
        {
            markers[i] = new google.maps.Marker(
               { position: store_locations[i],
                 map: map,
                 title: "Store " + (i+1)
               } );
            google.maps.event.addListener(markers[i], 'click', 
                function() {
                  markerClick(this);
                }
            );
        }
        function markerClick( mark )
        {
          for ( var m = 0; m < markers.length; ++m )
          {
            if ( markers[m] == mark ) 
            {
                 map.set_center(store_locations[m]);
                 map.set_zoom(16);
                 return;
            }
          }
        }
        document.getElementById("map_reset_button").style.display="block";
      }
    //]]>
    </script>
    <style type="text/css">
    * {margin:0;padding:0;}
    #map_container {position:relative;margin:10px;}
    #map_canvas {width:400px;height:400px;border:1px solid black;}
    #map_reset_button {display:none;position:absolute;top:24px;left:212px;border:1px solid black;}
    #map_reset_button a {width:119px;height:15px;line-height:15px;font-family:arial,sans-serif;color:black;border-style:solid;border-color:rgb(208, 208, 208) rgb(112, 112, 112) rgb(112, 112, 112) rgb(208, 208, 208);border-width:1px;text-decoration:none;display:block;font-size:12px;background-color:white;text-align:center;}
    #map_reset_button a:hover {border-color: rgb(112, 112, 112) rgb(208, 208, 208) rgb(208, 208, 208) rgb(112, 112, 112);}
    </style>
    </head>
    <body onload="initialize()">
    <div id="map_container">
      <div id="map_canvas"></div>
      <div id="map_reset_button"><a title="Reset Map" href="" onclick="initialize();return false;" onmouseover="window.status='';return true;" onmouseout="window.status=''return true;" onfocus="window.status='';return true;" onblur="window.status='';return true;">Reset Map</a></div>
    </div>
    </body>
    </html>
    I added a map reset button, but I didn't use any finesse with it. I just re-initialize the whole map. It's crude but effective.
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,449
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    No, JavaScript does not automatically convert strings into code. Period.

    Actually, you probably *could* do something like you are suggesting. *IF* you used eval( ) to convert the string into javascript code. But even so, you couldn't do
    Code:
    eval( "... point: 37.5, -101.2, ...")
    If you look at the base code that works, you will see that you *must* pass a LatLng object as the value of a point in there.

    So you *could* do:
    Code:
    eval( "... point: new google.maps.LatLng(37.5, -101.2), ...")
    But, really, this is a tacky way to do it. And it's also minorly fraught with peril: What happens if you get a bad value in your string and then eval( ) tosses its cookies at your feet? It's harder to find bugs from eval'ed string than when you construct the objects normally.

    *********

    Glad to see I was right about not being able to use the subscript in the event handler. I haven't lost touch with reality quite yet. <grin/>

  • #6
    New to the CF scene
    Join Date
    Sep 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I have a very similar issue and need some javascript help.

    I don't even consider myself a javascript newbie (below that), but need some help getting the google maps API in correctly. So forgive me for any stupid questions or comments.

    On a site we're developing, there is a built-in 'add to favorites' function that we're using as a suitcase (it's a travel planning site). Works like a dream, however I'd like to add a single google map with markers of everything that is in your 'suitcase'.

    Here is the idea (that I don't know how to do):
    1. Pull the string address out of a numbered div put in an array, geocode, and map (since the lat/long from the system aren't trustworthy, they were all 1/4 mile off)

    <div id="address-listing1">123 Main, Hometown, KS 66000</div>
    <div id="address-listing2">456 Second stree, Hometwon, KS 66000</div>

    etc
    etc... for however many items they have in their suitcase.

    I've played around with some code, but would be embarrassed to put here. I was proud that I got the individual maps and markers working using the string addresses as well. <self high five>

    Any help would be appreciated. I'll gladly buy you a beer.

    Thanks,

  • #7
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hi, I have a page with google maps v3, this works fine in develop mode but not online.
    In the develop mode this show all the makers that i put but in the production "online mode" this only put one marker.

    What's the difference betwen develop mode and online mode?
    develop mode = all works fine (all markers are visible)
    production/online mode = only one marker is visible

    Some idea?... Thanks


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •