显示谷歌地图的标记

时间:2018-02-01 12:13:56

标签: php google-maps laravel-5 marker

我一直想在谷歌地图上显示标记。我已经可以从数据库中获得经度和经度,但我的问题是它不会显示标记。这是我的代码。

    var map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 15,
        center: new google.maps.LatLng(10.3157, 123.8854),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    var locations = [
    <?php foreach($routes as $route){?>
        {
            "title": "{{ $route->destination }}",
            "lat": "{{ $route->lat }}",
            "lng": "{{ $route->lng }}"
        },

    <?php } ?>
   ];
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i].lat,locations[i].lng),
        icon: pin,
        map: map
    })

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i].title);
            infowindow.open(map, marker);
        }
    })(marker, i));

    console.log(locations[i].lat);
    console.log(locations[i].lng);
}

我尝试对纬度和经度进行console.log并成功显示,但标记不会显示。

1 个答案:

答案 0 :(得分:0)

您需要先创建infowindow。 您在点击事件中使用该变量但未创建该变量。

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 15,
    center: new google.maps.LatLng(10.3157, 123.8854),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});


var locations = [
<?php foreach($routes as $route){?>
    {
        "title": "{{ $route->destination }}",
        "lat": "{{ $route->lat }}",
        "lng": "{{ $route->lng }}"
    },

<?php } ?>
];

// Create infowindow here
var infowindow = new google.maps.InfoWindow();

for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i].lat,locations[i].lng),
    icon: pin,
    map: map
})

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
        infowindow.setContent(locations[i].title);
        infowindow.open(map, marker);
    }
  })(marker, i));

  console.log(locations[i].lat);
  console.log(locations[i].lng);
}
相关问题