首页 > 解决方案 > 需要帮助获取价值 Google Maps API .pac-container 类

问题描述

在用户点击时,当用户使用谷歌地图 api 输入位置时,我试图从“.pac-item”类中提取值。

我已阅读以下内容

https://developers.google.com/maps/documentation/javascript/places-autocomplete

由于.pac-container该类是动态生成的,因此我尝试使用事件处理程序来侦听.pac-container类,但无法获取用户单击 console.log 或事件日志的名称或位置。

$(document).on("click", ".pac-container", function(event) {

  var selected = $(this).val().trim();

  console.log(event);

  console.log("selected: " + selected);

});

I've also tried

$(document).on("click", ".pac-item", function(event) {

  var selected = $(this).val().trim();

  console.log(event);

  console.log("selected: " + selected);

});

我期待用户点击,点击任何地方的价值。例如,如果用户键入 portland 和.pac-container项目列表:

波特兰,或者,美国波特兰国际机场站 波特兰国际机场

如果用户单击波特兰,或者,我希望将该字符串保存到我选择的变量中。

现在,console.log 没有任何内容,console.log 也没有任何事件。

标签: javascriptjqueryapi

解决方案


好的,有点想出解决这个问题的办法。

在这部分谷歌地图代码中:

searchBox.addListener('places_changed', function () {

    var places = searchBox.getPlaces();

    googleLng = searchBox.bounds.ga.j;

    //give the lng some precision, as the open weather map api doesn't like 
    floating point numbers too long
    googleLng = googleLng.toPrecision(5);

    googleLat = searchBox.bounds.ma.j;

    //give the lat some precision, as the open weather map api doesn't like 
    floating point numbers too long
    googleLat = googleLat.toPrecision(5);

    console.log(googleLng);
    console.log(googleLat);

    clicktoCoord(googleLat, googleLng);


    if (places.length == 0) {
        return;
    }

    // Clear out the old markers.
    markers.forEach(function (marker) {
    marker.setMap(null);
    });

console.log(searchBox) 返回了一个对象,其中包含我在“.pac-item”列表中需要的数据(纬度和经度)。有了纬度和经度,我可以将其放入开放的天气图 ajax api 调用中,并且能够在用户单击的任何“pac-item”列表上获取天气状况。

希望这可以帮助某人。


推荐阅读