0

I'm brand new to perl and javascript and trying to get a javascript for loop to run through a perl array to insert markers into a google maps instance. The map is created and the for loop runs, but 5 of the same marker are inserted because the loop doesn't seem to be running correctly. Is there a better way to access this array in javascript?

@latlongarray = (0,0,20,20);
$length = @latlongarray;

{
print <<HTML;
<html>
<head>
<script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?&sensor=true">
    </script>

<script type="text/javascript">
var map ;
  function initialize() {
    var latlng = new google.maps.LatLng(0,0);
    var myOptions = {
     zoom: 2,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP // can be SATELLITE  ,HYBRID,          ROADMAP     or TERRAIN
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
{

var i;
for (i=0;i<=8;i=i+2)
{
var marker = add_marker($latlongarray[i],$latlongarray[i]); 
marker.setMap(map);
    }
    }

 }
  </script>
   <script type="text/javascript">
  function add_marker(lat,lng,title,box_html) {

    var infowindow = new google.maps.InfoWindow({
        content: box_html
});

var marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat,lng),
      map: map,
      title: title
});

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

  return marker;
 }
</script>

<title>Reverse IP Lookup & Locate</title>
</head>
 <body onload="initialize()">
   <div id="map_canvas" style="width:80%; height:80%"></div>
 </body>
HTML
exit;
}
1
  • 1
    You should never have got anywhere near writing this amount of code before you found that it wouldn't work. Always start with some simple code and make that work, then add to it and test it bit by bit. A large block of untested code is likely to have multiple bugs, and it is difficult to know where in that code to look for a fix.
    – Borodin
    Mar 20, 2012 at 15:47

2 Answers 2

1

Perl is server side. It executes BEFORE your Javascript. Perl just outputs HTML and Javascript, once it does that HTML and Javascript has no knowledge of your Perl variables.

You can make a loop in Perl that outputs the appropriate add_marker() Javascript code or you can output a Javascript array and then use a Javascript loop like you are now. You will never be able to reference Perl's array index from the Javascript loop.

0

As Cfreak pointed you are mixing up your Perl and Javascript code. I recently answered a very similar question in this post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.