Google Maps API не работает с AJAX на Битрикс

Я пытаюсь использовать Google API, и все было хорошо, кроме случаев, когда я пытался использовать его с AJAX. Итак, позвольте мне объяснить мою проблему. Я использую CMS Битрикс, и у меня есть задача использовать карты Google, и, конечно, они должны быть загружены с AJAX. Поэтому, когда пользователь заходит на мой сайт и нажимает кнопку, чтобы показать карты, все в порядке. Но когда он входит на вторую страницу предложений (которая загружается с AJAX), Google Maps ничего не показывает. И я не могу понять, почему? Вот мои скрипты с 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);
});
});

В моем блоке головы я просто включаю это:

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

А вот и мой PHP-код на CMS Битрикс

<?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>

2

Решение

Как обычно, ответ был действительно прост. Итак, проблема была в моем сценарии, и мне нужно было добавить $ (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();
});
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector