mardi 13 février 2018

JSON passed through Laravel view only accessible through listener function in JS script

I'm having an issue accessing a json file from a js script in a Laravel project.

I am using the Google maps API to add markers to a map, which are all currently hard-coded because I can only seem to access the json from within a listener function.

I am fully able to access my json through the placeMarker click listener, but when i try to make the "otherPlace" using json values, the values cannot be found. Not sure what's going on here.

Sorry for the likely noob question but I am stumped and couldn't find any similar questions.

Map script Example:

function myMap() {
    var mapProp= {
        center:new google.maps.LatLng(44.5458062,-83.54936229999996),
        zoom:8,
    };
    var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

    var place = new google.maps.LatLng(44.453,-83.45773609999998);
    var placeMarker = new google.maps.Marker({position: place});

    var otherPlace = new google.maps.LatLng(json.locations[4].lat,json.locations[4].lng);
    var otherPlaceMarker = new google.maps.Marker({position: otherPlace});

    placeMarker.setMap(map);
    otherPlaceMarker.setMap(map);

    placeMarker.addListener('click', function() {
        map.setZoom(13);
        map.setCenter(placeMarker.getPosition());
        console.log(json.locations[5].address);
        var infowindow = new google.maps.InfoWindow({
            //content: json.locations[5].name + "\r\nAddress: " + json.locations[5].address
        });

        infowindow.setContent(
            "<p>" + json.locations[5].name + "<br />" + json.locations[5].address + "<br/> <a href='#'>Get Directions</a> </p>"
        );
        infowindow.open(map,placeMarker);
    }); 
}

In my controller I grab the json file and pass it to the view

public function locations() {
        $path = storage_path() . "/json/locations.json"; 
        $json = json_decode(file_get_contents($path), true); 
        return view('home/locations', compact('json'));
}

In my locations.blade.php I add the map script and pass the json to javascript

@section('scripts')
<script src="/js/locationsMap.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=myMap"></script>
<script> 
    var json = {!! json_encode($json) !!};
</script>
@endsection



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire