【问题标题】:Laravel and google maps : foreach latitude/longitude show marker or mapLaravel 和谷歌地图:foreach 纬度/经度显示标记或地图
【发布时间】:2014-10-04 07:21:23
【问题描述】:

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

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

控制器的索引操作:

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

【问题讨论】:

  • 那么代码的哪一部分不起作用?第一个示例(使用一张地图,一个标记)是否适合您?
  • 不,该代码不起作用,因为我没有尝试加载一组纬度/经度。当我将 {{ $location->location_latitude }}, {{ $location->location_longitude }} 更改为 '50.9307','5.33248' 时,它显然有效。
  • 当您使用@foreach 时,它可以工作,但只显示最后一个?
  • 是的,只显示最后一个。

标签: javascript php laravel foreach laravel-4


【解决方案1】:

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

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

}

【讨论】:

  • 地图不见了,在控制台中我得到:未捕获的类型错误:无法读取 null 的属性 'lat'。
  • 您能否尝试在控制台中打印出locations 数组并检查它是否实际上是一个longlat 对数组?并确保模型中的所有经度和纬度值都是有效值。
  • 我的数组中有这个:var locations = [[50.930698394775,5.3324799537659], [51.054340362549,3.7174243927002],];但我不断收到此错误消息:Uncaught TypeError: Cannot read property 'lat' of null
  • 这个文件在哪里?你怎么能使用刀片?这不是js文件吗?
猜你喜欢
  • 2014-04-13
  • 2014-04-30
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
相关资源
最近更新 更多