【问题标题】:Modifying Google Maps API store locator to use JSON data in WordPress修改 Google Maps API 存储定位器以在 WordPress 中使用 JSON 数据
【发布时间】:2017-11-12 11:32:39
【问题描述】:

我正在寻找一种在 WordPress 中使用 Google Maps API 创建商店定位器的解决方案。虽然 WordPress 有许多插件,但我真的在寻找更定制的解决方案。以下是所需的参数:

  • 用户可以使用他们的位置(名称类型,例如利兹)或邮政编码来搜索位置。
  • 初始搜索表单位于主页上,提交后将重定向到地图页面,其中包含离它们最近的位置(基于半径),每个位置都有地图图钉
  • 如果用户已经在地图页面上,地图将显示所有可用位置(英国的 11 个位置)
  • 在地图页面中,用户还可以搜索他们的位置以优化结果
  • 在地图下方,每个位置都将显示为图块 (html),其中包含有关每家餐厅的信息,包括与您所在位置的距离
  • Tiles 将包含指向单个页面的链接,该页面包含有关所述位置的所有信息
  • 这是在 WordPress 上构建的,所以我的理想设置是每个位置都是 WordPress 页面,页面上有高级自定义字段 Google 地图

我做了什么

到目前为止,我已经使用 WordPress 页面创建了位置,每个页面都有自己的 ACF Google 地图作为自定义字段。通过使用自定义循环显示所有带有地图的页面,这将根据需要提供地图上的所有位置。

然后我浏览了 Google 自己的文档中的 example found here。我在一个单独的项目中使用 XML 制作了一个工作副本,但我现在正尝试使用 JSON 来做这个。

我目前所拥有的

这是我到目前为止的代码。

地图页面 - 自定义循环显示我设置的任何位置

<?php /* Template Name: Home */ 
get_header(); 

    $args = array(
        'post_type' => 'page',
        'posts_per_page' -1,
        'post__in' => array( 8, 10 )
    );

    $query = new WP_Query($args);

if ( $query->have_posts() ): ?>
<div class="wrapper">
    <!-- Search form here -->
    <div class="form-group">
        <input type="text" id="addressInput" class="form-control" placeholder="Enter location" />
    </div>

    <input type="button" id="searchButton" value="Search"/>
    <div class="acf-map">
        <?php
        while ( $query->have_posts() ): $query->the_post(); 
        $location = get_field('location'); 
    ?>
        <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
     <h4><a href="<?php the_permalink(); ?>" rel="bookmark"> <?php the_title(); ?></a></h4>
     <p class="address"><?php echo $location['address']; ?></p>
     </div>
        <?php endwhile;
      ?>
    </div>
</div>
<?php endif;
wp_reset_postdata();
get_footer();

标准的 ACF Maps jquery 加上来自谷歌地图商店定位器示例的功能 -- 这里的主要功能是 getUrl,它从我的 JSON 对象返回数据

(function($) {

/*
*  new_map
*
*  This function will render a Google Map onto the selected jQuery element
*
*  @type    function
*  @date    8/11/2013
*  @since   4.3.0
*
*  @param   $el (jQuery element)
*  @return  n/a
*/

function new_map( $el ) {

    // var
    var $markers = $el.find('.marker');


    // vars
    var args = {
        zoom        : 16,
        center      : new google.maps.LatLng(0, 0),
        mapTypeId   : google.maps.MapTypeId.ROADMAP,
        scrollwheel : false
    };


    // create map               
    var map = new google.maps.Map( $el[0], args);
    searchButton = document.getElementById("searchButton").onclick = getUrl;

    // add a markers reference
    map.markers = [];


    // add markers
    $markers.each(function(){

        add_marker( $(this), map );

    });


    // center map
    center_map( map );


    // return
    return map;

}

/*
*  add_marker
*
*  This function will add a marker to the selected Google Map
*
*  @type    function
*  @date    8/11/2013
*  @since   4.3.0
*
*  @param   $marker (jQuery element)
*  @param   map (Google Map object)
*  @return  n/a
*/

function add_marker( $marker, map ) {

    // var
    var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

    // create marker
    var marker = new google.maps.Marker({
        position    : latlng,
        map         : map
    });

    // add to array
    map.markers.push( marker );

    // if marker contains HTML, add it to an infoWindow
    if( $marker.html() )
    {
        // create info window
        var infowindow = new google.maps.InfoWindow({
            content     : $marker.html()
        });

        // show info window when marker is clicked
        google.maps.event.addListener(marker, 'click', function() {

            infowindow.open( map, marker );

        });
    }

}

/*
*  center_map
*
*  This function will center the map, showing all markers attached to this map
*
*  @type    function
*  @date    8/11/2013
*  @since   4.3.0
*
*  @param   map (Google Map object)
*  @return  n/a
*/

function center_map( map ) {

    // vars
    var bounds = new google.maps.LatLngBounds();

    // loop through all markers and create bounds
    $.each( map.markers, function( i, marker ){

        var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );

        bounds.extend( latlng );

    });

    // only 1 marker?
    if( map.markers.length == 1 )
    {
        // set center of map
        map.setCenter( bounds.getCenter() );
        map.setZoom( 16 );
    }
    else
    {
        // fit to bounds
        map.fitBounds( bounds );
    }

}

/* Custom function to search locations */


function search_locations() {
var address = document.getElementById("addressInput").value;
 var geocoder = new google.maps.Geocoder();
 geocoder.geocode({address: address}, function(results, status) {
   if (status == google.maps.GeocoderStatus.OK) {
    searchLocationsNear(results[0].geometry.location);
   } else {
     alert(address + ' not found');
   }
 });
}

/*
The function from google maps example, but I don't know
How to modify this for my needs 

function searchLocationsNear(center) {
 // this could be a static value
 // var radius = 50; 
 // for example

 var radius = 50;

//  var searchUrl = http://localhost:8888/googlemaps/
 var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
 getUrl(searchUrl, function(data) {
   var xml = parseXml(data);
   var markerNodes = xml.documentElement.getElementsByTagName("marker");
   var bounds = new google.maps.LatLngBounds();
   for (var i = 0; i < markerNodes.length; i++) {
     var id = markerNodes[i].getAttribute("id");
     var name = markerNodes[i].getAttribute("name");
     var address = markerNodes[i].getAttribute("address");
     var distance = parseFloat(markerNodes[i].getAttribute("distance"));
     var latlng = new google.maps.LatLng(
          parseFloat(markerNodes[i].getAttribute("lat")),
          parseFloat(markerNodes[i].getAttribute("lng")));

     createMarker(latlng, name, address);
     bounds.extend(latlng);
   }
   map.fitBounds(bounds);
   locationSelect.style.visibility = "visible";
   locationSelect.onchange = function() {
     var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
     google.maps.event.trigger(markers[markerNum], 'click');
   };
 });
}
*/

// Basic Ajax call to return some data from my markers object
function getUrl(url) {
  var xhttp, jsonData, parsedData;

  // check that we have access to XMLHttpRequest
  if(window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
  } else {
    // IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

     jsonData = this.responseText;

     parsedData = JSON.parse(jsonData);

     // test that we have some data
     parsedData.forEach(function(entry, index){
         console.log(entry.address);
     })

    }
  };
  xhttp.open("GET", 'http://localhost:8888/googlemaps/markers', true);
  xhttp.send(null);
}



/*
*  document ready
*
*  This function will render each map when the document is ready (page has loaded)
*
*  @type    function
*  @date    8/11/2013
*  @since   5.0.0
*
*  @param   n/a
*  @return  n/a
*/
// global var
var map = null;

$(document).ready(function(){

    $('.acf-map').each(function(){

        // create map
        map = new_map( $(this) );

    });

});

})(jQuery);

标记模板,显示将我的所有标记创建为 JSON - 这是我在 AJAX 请求中调用的 url

<?php

    /* Template Name: Markers */

    // initialise an arrays
    $markers = array();
    $locations = array();


    $args = array(
        'post_type' => 'page',
        'posts_per_page' -1,
        'post__in' => array( 8, 10 )
    );

    $query = new WP_Query($args);

    if($query->have_posts()) :
    $counter = 0;
        while($query->have_posts()) : $query->the_post();
        // the ACF custom field
        $location = get_field('location');
        // manually set radius
        $location['radius'] = 50;    

    foreach($location as $key => $value) {
        $locations[$key] = $value;
    }

    $markers[] = $locations;



        endwhile; 
    endif;

echo json_encode($markers);

当我单击搜索按钮时,数据会正确记录到控制台。我现在的问题是,如何修改上面链接的 Google Store Locator 示例,以便我可以显示离用户位置最近的位置?

我知道这是一个很长的问题,涉及很多部分,所以如果有什么我没有提到的,请问我。希望这一切都有意义。

谢谢

【问题讨论】:

    标签: javascript php json wordpress google-maps


    【解决方案1】:

    如果我没记错的话,我认为您只需要距离最短的单个结果。 这可以通过在集合markerNodes 中找到距离最小的键来完成。所以我们必须先找到那个钥匙。

    这里我更新searchLocationsNear(center)函数

    function searchLocationsNear(center) {
      clearLocations();
    
      var radius = document.getElementById('radiusSelect').value;
      var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
      downloadUrl(searchUrl, function(data) {
      var xml = parseXml(data);
      var markerNodes = xml.documentElement.getElementsByTagName("marker");
      var bounds = new google.maps.LatLngBounds();
      //First find element with least distance
      var minDisKey = 0; // assuming first element of markerNodes is minimum distance
      for (var i = 0; i < markerNodes.length; i++) {
        var minimum = parseFloat(markerNodes[minDisKey].getAttribute("distance"));
        var value = parseFloat(markerNodes[i].getAttribute("distance"));
        if(minimum > value) minDisKey = i;
      }
     // here we get element with least distance. 
     //So this key can be used for further processing with existing code.
        var id = markerNodes[minDisKey].getAttribute("id");
        var name = markerNodes[minDisKey].getAttribute("name");
        var name = markerNodes[minDisKey].getAttribute("name");
        var address = markerNodes[minDisKey].getAttribute("address");
        var distance = parseFloat(markerNodes[minDisKey].getAttribute("distance"));
        var latlng = new google.maps.LatLng(
            parseFloat(markerNodes[minDisKey].getAttribute("lat")),
            parseFloat(markerNodes[minDisKey].getAttribute("lng")));
    
        createOption(name, distance, minDisKey);
        createMarker(latlng, name, address);
        bounds.extend(latlng);
    
      map.fitBounds(bounds);
     });
    }
    

    应用后,您只能得到一个最接近的结果。

    【讨论】:

    • 感谢您的评论,但这并不是我想要的。我想我没有解释清楚。
    • 那么你在找什么。你能更新帖子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多