php - Google map API 无法在 Bitrix 上使用 AJAX

标签 php jquery ajax google-maps bitrix

我正在尝试使用 Google API,一切都很好,除了当我尝试将其与 AJAX 一起使用时。那么,让我解释一下我的麻烦。我正在使用 CMS Bitrix,并且我有一个使用 Google map 的任务,当然它们必须使用 AJAX 下载。因此,当用户进入我的网站并单击按钮显示 map 时,一切正常。但当他进入报价的第二页(使用 AJAX 下载)时,谷歌地图什么也没有显示。我不明白为什么?这是我的带有 PHP 代码的脚本。我希望你能帮助我 =)

var map, infoWindow;

//Add marker to the map, with additional info
function addMarker(myLatlng, street, side) {
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map
    });

    google.maps.event.addListener(marker, "click", function() {
            var contentString = "<h3>" + street + "</h3><i>" + side + "</i>";
            infoWindow.setContent(contentString);
            infoWindow.open(map, marker);
    });
};

//Initialization of the map
function initMap(result) {
    var arr = result[0]['coord'].split(',');
    var myLatlng = new google.maps.LatLng(arr[0], arr[1]);
    var mapOptions = {
        center: myLatlng,
        zoom: 18,
    };

    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    infoWindow = new google.maps.InfoWindow();


    //touch the map to close the info
    google.maps.event.addListener(map, "click", function() {
            infoWindow.close();
    });

    //if we want just to see single marker on the map
    if(result.length == 1) {
        arr = result[0]['coord'].split(',');
        myLatlng = new google.maps.LatLng(arr[0], arr[1]);

        addMarker(myLatlng, result[0]['street'], result[0]['side']);
    } else {
        //Many markers on the map
        var markersBounds = new google.maps.LatLngBounds();

        for(var i = 0; i < result.length; i++) {
            arr = result[i]['coord'].split(',');
            myLatlng = new google.maps.LatLng(arr[0], arr[1]);

            //for centralizing map
            markersBounds.extend(myLatlng);
            addMarker(myLatlng, result[i]['street'], result[i]['side']);
        }
        //set center of the map
        map.setCenter(markersBounds.getCenter(), map.fitBounds(markersBounds));
    }

    setTimeout(function() {google.maps.event.trigger(map, "resize");}, 600);
};



$(document).ready(function() {
    //Removing additional effects of fancybox
    $(".maphref").fancybox({
        touch: false
    });

    $(".allMarkers").fancybox({
        touch: false
    });


    //all citylights on the map
    $(".allMarkers").bind("click", function() {
        $.ajax ({
            url: "/citylights/getAllCoord.php",
            type: "POST",
            success: function(data) {
                var result = JSON.parse(data);
                initMap(result);
            }
        });
    });

    //single citylight on the map
    $(".maphref").bind("click", function() {
        var data = {'street': $(this).attr("data-street"), 'side': $(this).attr("data-side"), 'coord': $(this).attr("id")};
        var result = [data];
        initMap(result);
    });
});

在我的头 block 中,我只是包含以下内容:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXFNLY_Nozy_x9nRw4QRBPMNzHY2Pzepc&sensor=false"></script>

这是我在 CMS Bitrix 上的 PHP 代码

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
/** @var array $arParams */
/** @var array $arResult */
/** @global CMain $APPLICATION */
/** @global CUser $USER */
/** @global CDatabase $DB */
/** @var CBitrixComponentTemplate $this */
/** @var string $templateName */
/** @var string $templateFile */
/** @var string $templateFolder */
/** @var string $componentPath */
/** @var CBitrixComponent $component */

$this->setFrameMode(true);
?>
<a href="/citylights.xlsx">Download all citylights in .xlsx</a><br>
<a href="javascript:" class="allMarkers" data-fancybox data-src="#map">All citylights on a map</a>
<div class="clb"></div>
<?if($arParams["DISPLAY_TOP_PAGER"]):?>
    <?=$arResult["NAV_STRING"]?><br />
<?endif;?>
<?foreach($arResult["ITEMS"] as $arItem):?>
    <?
    $this->AddEditAction($arItem['ID'], $arItem['EDIT_LINK'], CIBlock::GetArrayByID($arItem["IBLOCK_ID"], "ELEMENT_EDIT"));
    $this->AddDeleteAction($arItem['ID'], $arItem['DELETE_LINK'], CIBlock::GetArrayByID($arItem["IBLOCK_ID"], "ELEMENT_DELETE"), array("CONFIRM" => GetMessage('CT_BNL_ELEMENT_DELETE_CONFIRM')));
    ?>
    <div class="citylight" id="<?=$this->GetEditAreaId($arItem['ID']);?>">
        <?if($street = $arItem["DISPLAY_PROPERTIES"]["ATT_STREET"]):?>
            <?if(!$arParams["HIDE_LINK_WHEN_NO_DETAIL"] || ($arItem["DETAIL_TEXT"] && $arResult["USER_HAVE_ACCESS"])):?>
                <a href="<?echo $arItem["DETAIL_PAGE_URL"]?>"><b><?=$street["VALUE"]?></b></a><br />
            <?endif;?>
        <?endif;?>

        <?if($side = $arItem["DISPLAY_PROPERTIES"]["ATT_SIDE"]):?>
            <span id="side"><?=$side["VALUE"]?></span><br>
        <?endif?>
        <?if($city = $arItem["DISPLAY_PROPERTIES"]["ATT_CITY"]):?>
            <i id="city"><?=$city["VALUE"]?></i><br><br>
        <?endif?>

        <a href="javascript:" class="maphref" data-fancybox data-src="#map" data-side="<?=$arItem["DISPLAY_PROPERTIES"]["ATT_SIDE"]["VALUE"]?>" data-street="<?=$arItem["DISPLAY_PROPERTIES"]["ATT_STREET"]["VALUE"]?>" id="<?=$arItem["DISPLAY_PROPERTIES"]["ATT_MAP"]["VALUE"]?>" name="<?=$arItem["NAME"]?>">Show n map</a><br><br>
        <?if($arParams["DISPLAY_PICTURE"]!="N" && is_array($arItem["PREVIEW_PICTURE"])):?>
            <?if(!$arParams["HIDE_LINK_WHEN_NO_DETAIL"] || ($arItem["DETAIL_TEXT"] && $arResult["USER_HAVE_ACCESS"])):?>
                <a href="<?=$arItem["DETAIL_PAGE_URL"]?>" title="<?=$arItem["PREVIEW_PICTURE"]["TITLE"]?>"><img id="preview"
                        src="<?=$arItem["PREVIEW_PICTURE"]["SRC"]?>"
                        height="166"
                        width="200"
                        alt="<?=$arItem["PREVIEW_PICTURE"]["ALT"]?>"/></a>
            <?else:?>
                <img id="preview" src="<?=$arItem["PREVIEW_PICTURE"]["SRC"]?>"  width="200" alt="<?=$arItem["PREVIEW_PICTURE"]["ALT"]?>"/>
            <?endif;?>
        <?endif?>
        <?if($arParams["DISPLAY_PICTURE"]!="N" && is_array($arItem["PREVIEW_PICTURE"])):?>
            <div style="clear:both"></div>
        <?endif?>
        <?if($date = $arItem["DISPLAY_PROPERTIES"]["ATT_DATE"]["DISPLAY_VALUE"]):?>
            <div class="reserved"><p class="if"><span class="busy"></span><?=$arItem["DISPLAY_PROPERTIES"]["ATT_STATUS"]["DISPLAY_VALUE"]?></p>
            <i class="to">до <?=$date?></i></div><br>
        <?else:?>
            <a href="javascript:" data-name="<?=$arItem["DISPLAY_PROPERTIES"]["ATT_STREET"]["VALUE"]?>" data-ref="<?=$arItem["DETAIL_PAGE_URL"]?>" class="buy" id="<?=$arItem['ID']?>" data-fancybox data-src="#hidden-form">Buy</a><br>
        <?endif?>
        <?if($adv = $arItem["DISPLAY_PROPERTIES"]["ATT_ADVANTAGE"]):?>
            <b><?=$adv["NAME"]?></b><br>
            <p class="advantage">
                <?foreach($adv["VALUE"] as $value):
                echo ($value.", ");
                endforeach?>
            </p>
        <?endif?>
    </div>
<?endforeach;?>
<div class="clb"></div>
<?if($arParams["DISPLAY_BOTTOM_PAGER"]):?>
    <br /><?=$arResult["NAV_STRING"]?>
<?endif;?>

<!-- Offers form -->
<form class="form-2" method="POST" action="" id="hidden-form">
    <div class="dop-info">
        <div class="dop-info-photo">
            <a href=""><img src="" width="100"></a>
        </div>
        <div class="dop-info-info">
            <h4></h4>
            <p></p>
        </div>
    </div>
    <span id="notice"></span><br>
    <input type="text" placeholder="Your name" name="name" id="name"><br>
    <input type="text" placeholder="Your e-mail" name="email" id="email"><br>
    <input type="text" placeholder="Your telephone" name="telephone" id="telephone"><br>
    <textarea placeholder="Your text" name="text" id="text"></textarea><br>
    <input type="button" value="Send" id="send">
    <input type="button" value="Close" class="close">
    <input type="hidden" name="city_id" value="<?=$arResult["ID"]?>" id="city_id">
    <input type="hidden" name="city_name" value="<?=$arResult["NAME"]?>" id="city_name">
    <input type="hidden" name="city_ref" value="<?=$arResult["DETAIL_PAGE_URL"]?>" id="city_ref">
</form>

<!-- Here would be our maps  -->
<div id="map"></div>

最佳答案

像往常一样,答案非常简单。所以,问题出在我的脚本中,我需要添加 $(document).ajaxComplete(....)。所以,现在我的脚本如下所示:

var map, infoWindow;

//Add marker to the map, with additional info
function addMarker(myLatlng, street, side) {
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map
    });

    google.maps.event.addListener(marker, "click", function() {
            var contentString = "<h3>" + street + "</h3><i>" + side + "</i>";
            infoWindow.setContent(contentString);
            infoWindow.open(map, marker);
    });
};

//Initialization of the map
function initMap(result) {
    var arr = result[0]['coord'].split(',');
    var myLatlng = new google.maps.LatLng(arr[0], arr[1]);
    var mapOptions = {
        center: myLatlng,
        zoom: 18,
    };

    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    infoWindow = new google.maps.InfoWindow();


    //touch the map to close the info
    google.maps.event.addListener(map, "click", function() {
            infoWindow.close();
    });

    //if we want just to see single marker on the map
    if(result.length == 1) {
        arr = result[0]['coord'].split(',');
        myLatlng = new google.maps.LatLng(arr[0], arr[1]);

        addMarker(myLatlng, result[0]['street'], result[0]['side']);
    } else {
        //Many markers on the map
        var markersBounds = new google.maps.LatLngBounds();

        for(var i = 0; i < result.length; i++) {
            arr = result[i]['coord'].split(',');
            myLatlng = new google.maps.LatLng(arr[0], arr[1]);

            //for centralizing map
            markersBounds.extend(myLatlng);
            addMarker(myLatlng, result[i]['street'], result[i]['side']);
        }
        //set center of the map
        map.setCenter(markersBounds.getCenter(), map.fitBounds(markersBounds));
    }

    setTimeout(function() {google.maps.event.trigger(map, "resize");}, 600);
};

function onLoadFunction() {
    //Removing additional effects of fancybox
    $(".maphref").fancybox({
        touch: false
    });

    $(".allMarkers").fancybox({
        touch: false
    });


    //all citylights on the map
    $(".allMarkers").bind("click", function() {
        $.ajax ({
            url: "/citylights/getAllCoord.php",
            type: "POST",
            success: function(data) {
                var result = JSON.parse(data);
                initMap(result);
            }
        });
    });

    //single citylight on the map
    $(".maphref").bind("click", function() {
        var data = {'street': $(this).attr("data-street"), 'side': $(this).attr("data-side"), 'coord': $(this).attr("id")};
        var result = [data];
        initMap(result);
    });
};


$(document).ajaxComplete(function() {
    onLoadFunction();
});

$(document).ready(function() {
    onLoadFunction();
});

关于php - Google map API 无法在 Bitrix 上使用 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877254/

相关文章:

php - PayPal 自适应支付错误 540031

javascript - 使用 javascript/jquery 从 Web 表单动态添加(和删除)一组文本元素

javascript - 以编程方式将 "Fit"可变长度 HTML 内容添加到单个打印页面?

php - 如何在phpexcel中设置普通表格标题

php - 当另一个表中不存在某些内容时执行此查询

javascript - jQuery 在没有任何标记的情况下获取 div 中的 html

javascript - Wicket ModalWindow 位置

javascript - jQuery.ajax : TypeError: Property 'xhr' of object #<Object> is not a function

jquery - 如何尽可能流畅地加载网页

php - 将内容插入数据库时​​自动刷新 div 标签