Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.

    var queryLat = [];
    var queryLng = [];

    @foreach($estates as $est)
        var result = $.getJSON({
                url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
            });

        result.done(function(data) {

            queryLat = data.results[0].geometry.location.lat;
            queryLng = data.results[0].geometry.location.lng;
        });
    @endforeach


    function initMap()
    {
        var options =
            {
                zoom : 10,
                center : {lat:34.652500, lng:135.506302}
            }

        var map  = new
            google.maps.Map(document.getElementById("map"), options);


        for (var i = 0; i < queryLat.length; i++)
        {
            var newMarker = new google.maps.Marker
            ({
                position: {lat: queryLat[i], lng: queryLng[i]} ,
                map: map
            });
        }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
384 views
Welcome To Ask or Share your Answers For Others

1 Answer

For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.

var queryLat = []; var queryLng = [];

@foreach($estates as $est)
    var result = $.getJSON({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
        });

    result.done(function(data) {

        queryLat.push(data.results[0].geometry.location.lat);
        queryLng.push(data.results[0].geometry.location.lng);
    });
@endforeach

function initMap()
{
    var options =
        {
            zoom : 10,
            center : {lat:34.652500, lng:135.506302}
        }

    var map  = new
        google.maps.Map(document.getElementById("map"), options);


    for (var i = 0; i < queryLat.length; i++)
    {
        var new_marker_str = "newMarker"+i;
        new_marker_str = new google.maps.Marker
        ({
            position: {lat: queryLat[i], lng: queryLng[i]} ,
            map: map
        });
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...