skip to Main Content

I’m doing this for an university assignment. I’m doing a web application based on the APIs of eBay and Google Maps. In practice, I make an API call to eBay and I put the results in a table. Now, clicking on the location of each item I got as a result, I want to geocode the address in a Google map. I wrote the PHP code for eBay API and the Javascript code for the Google Maps API as follows:

PHP code for eBay API

foreach($resp->searchResult->item as $item){
            $_i = 1;

            // Determine which price to display
            if ($item->sellingStatus->currentPrice) {
                $price = $item->sellingStatus->currentPrice;
            } else {
                $price = $item->listingInfo->buyItNowPrice;
            }

            $itemLocation = $item->location;
            // For each item, create a cell 
            $results .= "<tr> n<td $thisCellColor valign="top"> n";
            $results .= "<img src="$item->galleryURL"></td> n";
            $results .= "<td $thisCellColor valign="top"> <p><a href="" . $item->viewItemURL . "">" . $item->title . "</a></p>n";
            $results .= 'Shipped to: <b>' . $item->shippingInfo->shipToLocations . "</b><br> n";
            $results .= 'Current price: <b>$' . $price . "</b><br> n";
            $results .= "Location: <INPUT TYPE="button" id="$_i" VALUE="$itemLocation" onclick='clickToGeocode($_i);'  <br>";
            $results .= "</FORM> n";
            $results .= "</td> </tr> nn";
            $_i = $_i + 1;
        }

Javascript code for Google Maps

function clickToGeocode(id){
    var address = document.getElementById(id).value;
    document.write(id);
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
        });
    } else {
        alert('Geocode was not successful for the following reason: ' + status);
    }
    });
}

The problem is that every time I try to geocode a location the map goes to the location of the first item found in eBay..I mean the $_i (in PHP) and the id (in Javascript) is always 1..

How can I resolve this? Thanks.

2

Answers


  1. You’re resetting $_i to 1 each time. The initial value needs to be set before the loop, not within it:

    $_i = 1;
    
    foreach($resp->searchResult->item as $item)
    {
    
    Login or Signup to reply.
  2. Your html is broken:

    $results .= "Location: <input [..snip...] onclick='clickToGeocode($_i);'  <br>";
                                                                            ^---- here
    

    You never close the <input> tag, e.g. you’re missing a > at the indicated spot.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search