1
votes

My array from a PHP file looks like this:

[
 {"lat":"4.174475","lon":"73.509564","datetime":"2012-11-23 16:41:40"},
 {"lat":"5.17","lon":"73.50633754680894","datetime":"2012-11-23 05:00:00"},
 {"lat":"6.17","lon":"73.50633754680894","datetime":"2012-11-01 00:00:00"}
]

When I click the link #Three, it should generate 3 markers using the threeClick() function. Here is the function.

function threeClick () {
  $.getJSON('json.search.php?idcard=<?php echo $idcardno; ?>&limit=3', function(data) {
    var location;
    $.each(data, function (key, val) {
      addMarker(val.lat,val.lon);
    });
  }

The add marker function is like this (from: Plotting LatLng coordinates from Json Array on Google Map --- the markers all stack up in the same location)

function addMarker(lat,lng) {
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat,lng),
    map: map,
    icon: "images/mapIcons/red-dot.png"
  });
  markersArray.push(marker);
}

I generated the map using:

var map;
var markersArray = [];
function initMap() {
  var latlng = new google.maps.LatLng(4.174475, 73.509564);
  var myOptions = {
    zoom: 16,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
}

Can anybody suggest me how I can show the markers on click of a link? What is wrong with this code?

1
I don't see anything wrong with the code you posted. Please edit your post and add in the code you used for the event handler (the code that captures clicks on #Three and calls the threeClick() function).Ben Lee
Also, as @Andreas pointed out, please also include a description of the problem you encountered, including any error messages (or lack thereof).Ben Lee
@BenLee i used <a id="Three" onclick="threeClick" >three</a> . the problem is the markers arent comingjinni
@jinni, do you see any error messages in the javascript console?Ben Lee

1 Answers

1
votes

You said you used this:

<a id="Three" onclick="threeClick">three</a>

The problem is that threeClick by itself doesn't actually call the function. It just references it. You need parenthesis to call it, like this:

<a id="Three" onclick="threeClick()">three</a>

But it would be even better to use jQuery to attach the handler. So set your html like this:

<a id="Three" href="#">three</a>

And then add this to your javascript:

$('#Three').click(function() {
    threeClick();
    return false;
});

Note that the return false here is to prevent the '#' click default action (setting the url hash) from happening.