使用 Google Maps API 添加标记功能 [英] Add Marker function with Google Maps API

查看:18
本文介绍了使用 Google Maps API 添加标记功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Javascript,其中包括标准 Google Maps API initialize() 函数和自定义 addMarker() 函数.地图将正常加载,但标记不会添加到地图中.

I have the following Javascript that includes both the standard Google Maps API initialize() function and custom addMarker() function. The map will load fine however the marker does not get added to the map.

<script type="text/javascript">

    // Standard google maps function
    function initialize() {
        var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
        var myOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    // Function for adding a marker to the page.
    function addMarker(location) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }

    // Testing the addMarker function
    CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
    addMarker(CentralPark);

</script>

推荐答案

您在函数外部添加了添加标记方法调用,这导致它在 initialize 方法之前执行,该方法将在 google maps 脚本加载时调用,因此未添加标记,因为地图未初始化如下操作....创建单独的方法 TestMarker 并从 initialize 调用它.

You have added the add marker method call outside the function and that causes it to execute before the initialize method which will be called when google maps script loads and thus the marker is not added because map is not initialized Do as below.... Create separate method TestMarker and call it from initialize.

<script type="text/javascript">

    // Standard google maps function
    function initialize() {
        var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
        var myOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        TestMarker();
    }

    // Function for adding a marker to the page.
    function addMarker(location) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }

    // Testing the addMarker function
    function TestMarker() {
           CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
           addMarker(CentralPark);
    }
</script>

这篇关于使用 Google Maps API 添加标记功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆