duanmo6937 2017-03-21 21:59
浏览 39
已采纳

在PHP中调用AJAX后加载Google Maps选项

TL;DR: I have a MySQL table called company with 2 fields (lat, long) that I want to retrieve to load the address in Google Maps. So my function initMap(lat, long) in the file map.js needs those two arguments.

How can I pass those values after the AJAX call to the JS function that loads the map?

AJAX Function

function searchCompany() {
            $.ajax({
                type: 'post',
                url: 'ajax/search-company.php',

                data: {
                    data:idComp
                },
                success: function (response) {
                    document.getElementById("company").innerHTML=response;
// CALL INITMAP() HERE!
                    }
                });
            }

Google Maps script tag

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap">
</script>
<script src="js/map.js"></script>

Map.js

function initMap(lat, long) {

var location= new google.maps.LatLng(lat, long);
var mapEl= document.getElementById('map');
var mapOpt= {
    center: location,
    zoom: 15,
    panControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapEl, mapOpt);

// Add marker
var imgMarker= {
    url: 'img/marker.png',
    scaledSize: new google.maps.Size(50, 50)
}
var marker= new google.maps.Marker({
    position: location,
    map: map,
    icon: imgMarker
});

var contentString= '<div class="info-window">'+
                      '<h3>Info</h3>'+
                      '<div class="info-content">'+
                      '<p>Text</p>'+
                      '</div>'+
                      '</div>';

var infoWindow = new google.maps.InfoWindow({
    content: contentString,
    maxWidth: 400
});

mark.addListener('click', function() {
    infoWindow.open(map, marker);
});
}
  • 写回答

2条回答 默认 最新

  • doushajian2018 2017-03-21 22:07
    关注

    Your backend needs to return json for you to grab with jQuery's ajax

    <?php
    ....
    $result = ['lat'=>12.34, lng=>56.78];
    
    echo json_encode($result);
    

    then you can receive it as an object instead of html

    $.ajax({
      type: 'post',
      url: 'ajax/search-company.php',
      dataType:'json',
      data: {
         data:idComp
      },
      success: function (response) {
        // response is an object with lat and lng properties
        initMap(response.lat, response.lng);
      }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀