简体   繁体   中英

Change the for-loop to fit a json-array?

i got this code from a tutorial and it is fully functional:

  var sites = [
    ['Mount Evans', 39.58108, -105.63535, 4, 'This is Mount Evans.'],
    ['Irving Homestead', 40.315939, -105.440630, 2, 'This is the Irving Homestead.'],
    ['Badlands National Park', 43.785890, -101.90175, 1, 'This is Badlands National Park'],
    ['Flatirons in the Spring', 39.99948, -105.28370, 3, 'These are the Flatirons in the spring.']
];



    function setMarkers(map, markers) {

        for (var i = 0; i < markers.length; i++) {
            var sites = markers[i];
            var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
            var marker = new google.maps.Marker({
                position: siteLatLng,
                map: map,
                title: sites[0],
                html: sites[4]



     });

        var contentString = "Some content";

        google.maps.event.addListener(marker, "click", function () {
            infowindow.setContent(this.html);
            infowindow.open(map, this);
        });
    }
}

it displays markers on a map with the information from the array.

I want to change the for-loop so it fits my array. because when i try this with my array, the maps dont even show up..

<?php

include_once'config/connect.php';

$search= $_POST['search'];
$search = stripslashes($search);

$search = mysql_real_escape_string($search);

$sql= "select * from venue where vID in (select vID from sv where sID in (select sID from sports where sN = '$search'));";

$result=mysql_query($sql)or die(mysql_error()); 

 $data1 = mysql_fetch_array($result);
 $array = array($data1['latitude'], $data1['longitude'], $data1['venue']);

echo json_encode($array);
?> 


    var sites = <?php echo json_encode($array); ?>;

this prints exactly as it should

sites[0] = 57.7865 //latitude
sites[1] = 11.7986 //longitude
sites[2] = fjaderborgen //venue

but it doesnt work with the map code.

I need to change the loop somehow, how can i do this?

Actually, you don't want a loop at all, since you're only defining one site (despite the variable name " sites ").

var siteLatLng = new google.maps.LatLng(sites[0], sites[1]);
var marker = new google.maps.Marker({
  position: siteLatLng,
  map: map,
  title: sites[2],
  html: "This is " + sites[2]
});

google.maps.event.addListener(marker, "click", function () {
  infowindow.setContent(this.html);
  infowindow.open(map, this);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM