使用Google Places Nearby Search API无法按距离排序结果
Let me break down why your request isn't returning results sorted by distance, even after removing the radius parameter:
Key Rules for rankBy=distance
Google's Places Nearby Search has strict requirements when using rankBy=distance that you might have overlooked:
You CANNOT use
radiusalongsiderankBy=distance
Even if you tried removing it later, double-check that your final request doesn't include both parameters. Having both will override the distance ranking behavior—this is a hard restriction in the API spec.Ensure only one ranking parameter is present
Make sure you're not accidentally including other ranking-related parameters (likerankBy=prominencesomewhere in the request). The API will default to prominence if there's a conflict.Verify your parameter formatting
Yourkeyword=k rautahas a space—encode it properly askeyword=k%20rautain the URL. While some clients handle spaces automatically, unencoded spaces can cause unexpected parsing issues that break the ranking logic.
Step-by-Step Fix
- Construct a valid request URL that adheres to the rules:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=60.16915,24.9293937&rankBy=distance&keyword=k%20rauta&key=YOUR_API_KEY - Clear any cached responses—sometimes old, incorrectly ranked results might be stored by your client or proxy.
- Check the API response for errors
Look for anerror_messagefield in the JSON response. If the API is rejecting your request for any reason (like invalid parameters), it won't apply the correct sorting.
Why This Works
When rankBy=distance is used correctly, the API will return results sorted strictly by ascending distance from your specified location coordinate. Any deviation usually comes from violating the parameter constraints mentioned above.
内容的提问来源于stack exchange,提问作者Mizlul




