javascript - Laravel 和谷歌地图 : foreach latitude/longitude show marker or map

标签 javascript php laravel foreach laravel-4

我有一个带有纬度和经度字段的位置表。

对于每个位置,我都想要一个新 map (或者更好的新标记),它使用表格位置中的纬度和经度在 map 上显示一个城市。

Controller 的索引 Action :

public function index()
    {
        $locations = Location::all();

        $locations->location_latitude = Input::get('location_latitude');
        $locations->location_longitude = Input::get('location_longitude');

        return View::make('forecasts.index')
            ->with('locations', $locations);
    }

带标记的谷歌地图:

function initialize() {

    var map_canvas = document.getElementById('map_canvas');

    var location = new google.maps.LatLng({{ $location->location_latitude }}, {{ $location->location_longitude }});

    var map_options = {
        center: location,
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(map_canvas, map_options)

    var marker = new google.maps.Marker({
        position: location,
        map: map,
    });

    marker.setMap(map);

  }

  google.maps.event.addDomListener(window, 'load', initialize);

当我这样做时,它只显示最后插入的纬度/经度的城市:

@foreach($locations as $location)

   var location = new google.maps.LatLng({{ $location->location_latitude }}, {{ $location->location_longitude }});

@endforeach

最佳答案

这可能是因为在循环遍历集合时您实际上并没有创建单独的标记。

function initialize() {

    var map_canvas = document.getElementById('map_canvas');

    // Initialise the map
    var map_options = {
        center: location,
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)

    // Put all locations into array
    var locations = [
    @foreach ($locations as $location)
        [ {{ $location->location_latitude }}, {{ $location->location_longitude }} ]     
    @endforeach
    ];

    for (i = 0; i < locations.length; i++) {
        var location = new google.maps.LatLng(locations[i][0], locations[i][1]);

        var marker = new google.maps.Marker({
            position: location,
            map: map,
        }); 
    }

    // marker.setMap(map); // Probably not necessary since you set the map above

}

关于javascript - Laravel 和谷歌地图 : foreach latitude/longitude show marker or map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25243701/

相关文章:

javascript - 我可以将彩盒固定在头上吗?

php - Google Analytics PHP(发送信息)

php - 获取mysql查询的上一个和下一个id值

php - Laravel 5.1 - 模型工厂错误种子

javascript - jQuery 函数在 Laravel 中不起作用

javascript - 将文本转换为 css

javascript:构造函数与一次性使用的揭示模块模式

javascript - 在 firefox 中,如何在本地文件中运行 javascript,例如文件 :///C:/play/my. html

php - laravel 单例模式如何反射(reflect)后续调用的变化?

php - Laravel:有没有办法删除数据库查询子句?