简体   繁体   中英

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode() , so I added that part into my loop.

If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.

I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.

How can I fix this to show all locations in the correct way?

// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
    // Create the map canvas with options.
    var map = new google.maps.Map(document.getElementById('map-canvas'), {
        scrollwheel: false,
        draggable: true,
        mapTypeControl: false,
        zoom: zoomlevel,
        center: new google.maps.LatLng(40.577453, 2.237408),  // Center the map at this location. 
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    var marker, i;

    // For each location in the array...
    for (i = 0; i < locations.length; i++)
    {  
        // Get the coordintes for the address.
        var geocoder = new google.maps.Geocoder();

        var address = locations[i][5];  // ***This variable will output the address.***

        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var location_latitude  = results[0].geometry.location.lat();
                var location_longitude = results[0].geometry.location.lng();

                // Create the map marker icon (SVG file).
                var marker_icon = {
                    url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
                    anchor: new google.maps.Point(25,50),
                    scaledSize: new google.maps.Size(50,50)
                }

                // Place the marker on the map.
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(location_latitude, location_longitude),
                    map: map,
                    icon: marker_icon
                });
            } 
        }); 
    }
}

This is how I am placing map markers on Google Maps:

<script type="text/javascript">
    let map;
    let parameters;
    function initMap() {
        map = new google.maps.Map(document.getElementById("map"), {
            center: { lat: @Model.Latitude , lng: @Model.Longitude },
            zoom: @Model.Zoom,
        });
        @foreach (var asset in dbService.Assets)
        {
            @if (asset.State != Models.AssetState.deleted)
            {
                @:parameters = 'Id = @asset.Id\n' + 'Temperature = @asset.Temperature\n' + 'Moisture = @asset.Moisture\n';
                @:setMarker('@asset.Latitude', '@asset.Longitude', '@asset.State');
            }
        }
    }

    function getIconByState(state) {
        if (state == 'non_functional') {
            return 'non-functional.png';
        }
        else if (state == 'under_maintenance') {
            return 'under-maintenance.png';
        }
        else if (state == 'functional') {
            return 'functional.png';
        }
    }

    function setMarker(lat, lng, state) {
        var markerjs = new google.maps.Marker({
            icon: getIconByState(state),
            position: new google.maps.LatLng(lat, lng),
        });
        markerjs.setMap(map);
        let infowindow = new google.maps.InfoWindow({
            content: parameters,
        });
        markerjs.addListener("click", () => {
            infowindow.open(map, markerjs);
        });
    }
</script>

//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
        defer></script>

In this code, I use the latitude and longitude to place a marker on the Map.

If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:

<script type="text/javascript">
    function setCoordinates() {
        let address = document.getElementById('zip').value;
        if (address) {
            let geocoder = new google.maps.Geocoder();
            if (geocoder) {
                geocoder.geocode({ 'address': address }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        document.getElementById('latitude').value = results[0].geometry.location.lat();
                        document.getElementById('longitude').value = results[0].geometry.location.lng();
                    }
                    else {
                        console.log('geocoding failed');
                    }
                });
            }
        }
        else {
            alert('Please enter postal code to use this functionality');
        }
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM