首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google Maps geocode()循环放置标记

Google Maps geocode()循环放置标记
EN

Stack Overflow用户
提问于 2021-04-29 11:46:29
回答 1查看 31关注 0票数 1

我有一个包含位置数据的数组,其中一项是地址。加利福尼亚州旧金山主街123号我想将这个地址转换为坐标,然后使用这些坐标在地图上绘制一个标记。要做到这一点,我知道我需要使用geocode(),所以我将这部分添加到我的循环中。

如果我在数组中使用纬度和经度而不是地址,我可以让它正常工作。但是,因为我在循环中添加了geocode(),所以我只能获取数组中显示标记的第一个位置。

我在这里看到了一些类似的问题,建议使用callback(),但我不理解它。我也看到了一个建议,为geocode()增加0.5秒的延迟,这对海报有效,但评论说,在较慢的网速下,它可能不会加载所有位置。

我如何解决这个问题,以便以正确的方式显示所有位置?

代码语言:javascript
复制
// 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
                });
            } 
        }); 
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-29 11:58:39

这就是我在Google Maps上放置地图标记的方式:

代码语言:javascript
复制
<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>

在这段代码中,我使用纬度和经度在地图上放置一个标记。

如果您想从地址中提取纬度和经度,请按以下方式使用地理编码器API:

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67310763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档