Using Custom Field to generate distance from another location

I am using this tutorial to calculate the distance between two addresses using Google Maps.

I am looking to output the distance between the origin address, which is a fixed point, and the destination address, which is dependent on what the user inputs in the _ct_text_53ea3270e6e6d field.

It works fine pulling from one address, but if it pulls from multiple maps, it only shows the distance from one of the maps, not from each of them.

Here is a screenshot showing the problem. In the screenshot, it is successfully pulling the distance from the first address, which is within very close proximity of the origin address. However, the second result has an address that is ~10 miles away, but it is not grabbing that address and only repeats the first result's output.

Here is the code I'm using to get this distance:

<?php
$field_value =  do_shortcode('[ct id="_ct_text_53ea3270e6e6d" property="title | description | value"]');

// Our parameters
$params = array(
    'origin'        => '900 South Crouse Ave, Syracuse, NY, 13210',
    'destination'   => $field_value,
    'sensor'        => 'true',
    'units'         => 'imperial'
);

// Join parameters into URL string
foreach($params as $var => $val){
    $params_string .= '&' . $var . '=' . urlencode($val);
}

// Request URL
$url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');

// Make our API request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);

// Parse the JSON response
$directions = json_decode($return);
?>
<strong>Distance from Campus</strong>:
<?php
// Print distance
printf($directions->routes[0]->legs[0]->distance->text);
?>

I just need a second look to see why this happening.

  • Larry

    I am using a plugin called Advanced Custom Post Search in conjunction with CustomPress.

    It is in a search results loop page. Here is the full code for that page:

    <?php
    //New results loop
    $acps_results = new WP_Query( $this->acps_args );
    $template = get_option('template');
    $search = ( isset($this->acps_args['s']) ) ? true : false ;
    
    //Standard loop
    if( $acps_results->have_posts() ): ?>
    
    <?php $acps_result_label = ($acps_results->post_count > 1) ? 'Results' : 'Result'; ?>
    
    <header class="page-header">
        <?php if( $search ): ?>
          <h1 class="page-title"><?php printf( __( '%s Search %s for: %s', 'acps' ), $acps_results->post_count, $acps_result_label, $this->acps_args['s'] ); ?></h1>
        <?php else: ?>
            <h1 class="page-title"><?php _e('Search Results','acps');?></h1>
        <?php endif; ?>
    </header>
    
    <?php while( $acps_results->have_posts() ) : $acps_results->the_post(); ?>
    
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    
        <?php if( has_post_thumbnail() ): ?>
            <?php if( $template != 'cobalt' ): ?>
            <div class="entry-header">
            <?php endif; ?>
            <?php if( $template != 'cobalt' ): ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    
        <?php if( $template == 'cobalt' ): ?>
            <header class="entry-header">
        <?php endif; ?>
    
    <div class="alignleft">
    <?php
    										the_content( __( 'More info <span class="meta-nav">&rarr;</span>', 'cobalt' ) );
    										wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'cobalt' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
    </div>
    
        <div class="entry-meta alignleft" style="margin-left:20px;">
            <?php the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
    
            if ( ! post_password_required() && ( comments_open() || get_comments_number() ) ) :
            ?>
    
            <?php
            endif;
    
            //edit_post_link( __( 'Edit', 'acps' ), '<span class="edit-link">', '</span>' ); ?>
    <br>
    <h3><?php echo do_shortcode('[ct id="_ct_text_53ea321fd8356" property="title | description | value"]'); ?></h3>
    
    <p>
    <strong>Phone:</strong> <a href="tel:<?php echo do_shortcode('[ct id="_ct_text_53ea330659759" property="value"]'); ?>"><?php echo do_shortcode('[ct id="_ct_text_53ea330659759" property="title | description | value"]'); ?></a>
    <?php
    $field_value = do_shortcode('[ct id="_ct_text_53ea3433519ab" ]');
    if($field_value !== '') { ?> <br>
    <strong>Email:</strong> <a href="mailto:<?php echo do_shortcode('[ct id="_ct_text_53ea3433519ab" property="value"]'); ?>"><?php echo do_shortcode('[ct id="_ct_text_53ea3433519ab" property="title | description | value"]'); ?></a><?php } ?>
    <?php
    $field_value = do_shortcode('[ct id="_ct_text_53ea332521cb2" ]');
    if($field_value !== '') { ?> <br>
    <strong>Website:</strong> <a href="<?php echo do_shortcode('[ct id="_ct_text_53ea332521cb2" property="value"]'); ?>"><?php echo do_shortcode('[ct id="_ct_text_53ea332521cb2" property="value"]'); ?></a><?php } ?>
    </p><br>
    <h4>Address</h4>
    <?php echo do_shortcode('[ct id="_ct_text_53ea3270e6e6d" property="title | description | value"]'); ?><br><br>
    <?php
    $field_value =  do_shortcode('[ct id="_ct_text_53ea3270e6e6d" property="title | description | value"]');
    
    // Our parameters
    $params = array(
        'origin'        => '900 South Crouse Ave, Syracuse, NY, 13210',
        'destination'   => $field_value,
        'sensor'        => 'true',
        'units'         => 'imperial'
    );
    
    // Join parameters into URL string
    foreach($params as $var => $val){
        $params_string .= '&' . $var . '=' . urlencode($val);
    }
    
    // Request URL
    $url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');
    
    // Make our API request
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $return = curl_exec($curl);
    curl_close($curl);
    
    // Parse the JSON response
    $directions = json_decode($return);
    ?>
    <strong>Distance from Campus</strong>:
    <?php
    // Print distance
    printf($directions->routes[0]->legs[0]->distance->text);
    ?>
    
     </div>
    <div class="clear"></div>
    
    <hr />
    
        <?php if( $template == 'cobalt3' ): ?>
            </header>
        <?php endif; ?>
    
        <div class="entry-summary">
            <?php the_excerpt(); ?>
        </div>
    
        </article>
    
        <?php
        endwhile;
        else:
        ?>
    
        <header class="page-header">
            <h1 class="page-title"><?php _e( 'Nothing Found', 'acps' ); ?></h1>
        </header>
    
        <div class="page-content">
            <p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with different options.', 'acps' ); ?></p>
            <?php echo do_shortcode('[acps id="'.$this->acps_form_id.'"]'); ?>
        </div>
    
    <?php
    endif;
    ?>
  • Jose

    Hey @Larry,

    As far as I can see, the implementation is correct.
    The other fields seems to be loading the correct information, as per your screenshot.

    I would suggest to add a var_dump to be totally sure that the destination value is being picked correctly:

    $field_value =  do_shortcode('[ct id="_ct_text_53ea3270e6e6d" property="title | description | value"]');
    var_dump($field_value);

    If you find that the destination value is correct, then I would say that this is related to a cache issue.

    The CURL transfer may be getting a cached response.

    Try adding the following to the curl options:
    curl_setopt($curl, CURLOPT_FRESH_CONNECT, TRUE);

    Please let me know if this helps. There are more things to try, but I would need access to your site. Let's try these suggestion first :slight_smile:

    Cheers,
    Jose

  • Jose

    No problem :slight_smile:

    In your parameters, try adding a random token to avoid the cached response:

    // Our parameters
    $params = array(
        'origin'        => '900 South Crouse Ave, Syracuse, NY, 13210',
        'destination'   => $field_value,
        'sensor'        => 'true',
        'units'         => 'imperial',
        'random'   => rand()
    );

    Also add some var_dump to track where the issue is happening:

    // Parse the JSON response
    $directions = json_decode($return);
    
    var_dump($url);//Check if the url parameters are correct.
    var_dump($return);//Check if the return was cached or not
    var_dump($directions);//Check if the json_decode didn't break anything.

    Please keep me posted.

    Cheers,
    Jose

  • Larry

    Those var_dumps definitely gave insight.

    For the URL dump, this is for the first result:

    string(185) "http://maps.googleapis.com/maps/api/directions/json?origin=900+South+Crouse+Ave%2C+Syracuse%2C+NY%2C+13210&destination=103+Marshall+St%2C+Syracuse%2C+NY+13210&sensor=true&units=imperial"

    ^ This one is completely correct

    string(326) "http://maps.googleapis.com/maps/api/directions/json?origin=900+South+Crouse+Ave%2C+Syracuse%2C+NY%2C+13210&destination=103+Marshall+St%2C+Syracuse%2C+NY+13210&sensor=true&units=imperial&origin=900+South+Crouse+Ave%2C+Syracuse%2C+NY%2C+13210&destination=115+Suburban+Park+Drive%2C+Manlius%2C+NY+13104&sensor=true&units=imperial"

    ^ This is the second result. As you can see, it is pulling from the first and second result. It is setting the destination and origin twice.

    For the return cache results, it is showing this for both:

    string(3477) "{ "routes" : [ { "bounds" : { "northeast" : { "lat" : 43.0416329, "lng" : -76.13641729999999 }, "southwest" : { "lat" : 43.0401029, "lng" : -76.13669089999999 } }, "copyrights" : "Map data ©2014 Google", "legs" : [ { "distance" : { "text" : "0.1 mi", "value" : 192 }, "duration" : { "text" : "1 min", "value" : 41 }, "end_address" : "103 Marshall Street, Syracuse, NY 13210, USA", "end_location" : { "lat" : 43.0416309, "lng" : -76.13641729999999 }, "start_address" : "900 South Crouse Avenue, Syracuse University, North Zone, Syracuse, NY 13210, USA", "start_location" : { "lat" : 43.0401029, "lng" : -76.13657909999999 }, "steps" : [ { "distance" : { "text" : "0.1 mi", "value" : 172 }, "duration" : { "text" : "1 min", "value" : 37 }, "end_location" : { "lat" : 43.0416329, "lng" : -76.13666099999999 }, "html_instructions" : "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Crouse Ave\u003c/b\u003e toward \u003cb\u003eWaverly Ave\u003c/b\u003e", "polyline" : { "points" : "sgueGrluoMA?IAE?E@E@E@IBOHC@E@C?K?c@AeA?eAAi@A" }, "start_location" : { "lat" : 43.0401029, "lng" : -76.13657909999999 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "66 ft", "value" : 20 }, "duration" : { "text" : "1 min", "value" : 4 }, "end_location" : { "lat" : 43.0416309, "lng" : -76.13641729999999 }, "html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003eMarshall St\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003eDestination will be on the left\u003c/div\u003e", "maneuver" : "turn-right", "polyline" : { "points" : "equeGbmuoM?o@" }, "start_location" : { "lat" : 43.0416329, "lng" : -76.13666099999999 }, "travel_mode" : "DRIVING" } ], "via_waypoint" : [] } ], "overview_polyline" : { "points" : "sgueGrluoMW?e@PYByEE?o@" }, "summary" : "S Crouse Ave", "warnings" : [], "waypoint_order" : [] } ], "status" : "OK" } "

    This is clearly a problem as the code is not recognizing there are more than one addresses and they are separate from each other.

    Here is what the json_decode is outputting for both results:

    object(stdClass)#460 (2) { ["routes"]=> array(1) { [0]=> object(stdClass)#430 (7) { ["bounds"]=> object(stdClass)#404 (2) { ["northeast"]=> object(stdClass)#458 (2) { ["lat"]=> float(43.0416329) ["lng"]=> float(-76.1364173) } ["southwest"]=> object(stdClass)#402 (2) { ["lat"]=> float(43.0401029) ["lng"]=> float(-76.1366909) } } ["copyrights"]=> string(22) "Map data ©2014 Google" ["legs"]=> array(1) { [0]=> object(stdClass)#401 (8) { ["distance"]=> object(stdClass)#400 (2) { ["text"]=> string(6) "0.1 mi" ["value"]=> int(192) } ["duration"]=> object(stdClass)#399 (2) { ["text"]=> string(5) "1 min" ["value"]=> int(41) } ["end_address"]=> string(44) "103 Marshall Street, Syracuse, NY 13210, USA" ["end_location"]=> object(stdClass)#398 (2) { ["lat"]=> float(43.0416309) ["lng"]=> float(-76.1364173) } ["start_address"]=> string(81) "900 South Crouse Avenue, Syracuse University, North Zone, Syracuse, NY 13210, USA" ["start_location"]=> object(stdClass)#397 (2) { ["lat"]=> float(43.0401029) ["lng"]=> float(-76.1365791) } ["steps"]=> array(2) { [0]=> object(stdClass)#396 (7) { ["distance"]=> object(stdClass)#395 (2) { ["text"]=> string(6) "0.1 mi" ["value"]=> int(172) } ["duration"]=> object(stdClass)#394 (2) { ["text"]=> string(5) "1 min" ["value"]=> int(37) } ["end_location"]=> object(stdClass)#393 (2) { ["lat"]=> float(43.0416329) ["lng"]=> float(-76.136661) } ["html_instructions"]=> string(66) "Head north on S Crouse Ave toward Waverly Ave" ["polyline"]=> object(stdClass)#392 (1) { ["points"]=> string(46) "sgueGrluoMA?IAE?E@E@E@IBOHC@E@C?K?c@AeA?eAAi@A" } ["start_location"]=> object(stdClass)#391 (2) { ["lat"]=> float(43.0401029) ["lng"]=> float(-76.1365791) } ["travel_mode"]=> string(7) "DRIVING" } [1]=> object(stdClass)#390 (8) { ["distance"]=> object(stdClass)#389 (2) { ["text"]=> string(5) "66 ft" ["value"]=> int(20) } ["duration"]=> object(stdClass)#388 (2) { ["text"]=> string(5) "1 min" ["value"]=> int(4) } ["end_location"]=> object(stdClass)#387 (2) { ["lat"]=> float(43.0416309) ["lng"]=> float(-76.1364173) } ["html_instructions"]=> string(107) "Turn right onto Marshall St
    Destination will be on the left
    " ["maneuver"]=> string(10) "turn-right" ["polyline"]=> object(stdClass)#386 (1) { ["points"]=> string(13) "equeGbmuoM?o@" } ["start_location"]=> object(stdClass)#385 (2) { ["lat"]=> float(43.0416329) ["lng"]=> float(-76.136661) } ["travel_mode"]=> string(7) "DRIVING" } } ["via_waypoint"]=> array(0) { } } } ["overview_polyline"]=> object(stdClass)#384 (1) { ["points"]=> string(23) "sgueGrluoMW?e@PYByEE?o@" } ["summary"]=> string(12) "S Crouse Ave" ["warnings"]=> array(0) { } ["waypoint_order"]=> array(0) { } } } ["status"]=> string(2) "OK" }

    It is also not recognizing there are separate addresses to pull from.

  • Jose

    Ok, I see the issue.

    The scope of $params_string is causing problems. It is increasing with each iteration since you never reset the value and you just keeps concatenating the strings.

    Try changing this:

    // Join parameters into URL string
    foreach($params as $var => $val){
        $params_string .= '&' . $var . '=' . urlencode($val);
    }

    Into this:
    $params_string = http_build_query($params);

    Note that http_build_query() is a PHP built-in method that makes basically the same as your foreach loop. The difference here is that we are not concatenating each string, but instead resetting the value of $params_string.

    Please let me know if it works in this way. (keep the var_dumps running just in case).

    Cheers,
    Jose

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.