问题
I have an entity which has latitude and longitude fields.
Now I have a address, I know the latitude and longitude of this address, I want to retrieve the records within 3 miles.
How to do it using FetchXML?
回答1:
You won't be able to do this directly via FetchXml as geocoding is not offered as a feature.
This means you'll need to start rolling something by hand which will not be easy. This site has a pretty good overview of what you'd need to do (even if the language is different to what you'd likely use with CRM).
One option may be to relax your requirement and just use FetchXml to look for records with a longitude +/- 1.5 miles and latitude +/- 1.5 miles (which of course queries an area shaped like a square rather than a radius).
If you need to be more strict, you could try to rewrite the following MySQL (i.e. not MSSQL!) query and use it alongside some sort of QueryExpression instead? So, for example, a query expression to determine a rough subset of data, as above (e.g. where longitude and latitude is with 1.5 miles of central point) and then after returning those results, for each one calculate if it falls within the desired radius...
SELECT id, X(gm_coor) AS latitude, Y(gm_coor) AS longitude,
ATAN2(
SQRT(
POW(COS(RADIANS(__LAT__)) *
SIN(RADIANS(Y(gm_coor) - __LNG__)), 2) +
POW(COS(RADIANS(X(gm_coor))) * SIN(RADIANS(__LAT__)) -
SIN(RADIANS(X(gm_coor))) * COS(RADIANS(__LAT__)) *
COS(RADIANS(Y(gm_coor) - __LNG__)), 2)),
(SIN(RADIANS(X(gm_coor))) * SIN(RADIANS(__LAT__)) +
COS(RADIANS(X(gm_coor))) * COS(RADIANS(__LAT__)) *
COS(RADIANS(Y(gm_coor) - __LNG__)))
) * 6372.795 AS distance
FROM geocoded
HAVING distance < [RANGE IN KILOMETRES]
回答2:
I can think of two options off hand
1) Use the filtered views inside SQL and calculate the great circle distance formula. This is the cleanest way, but isn't fetch.
2) Fetch all of the results within +/- .02 for lat/lng of the desired point. Then use the great circle distance formula (and javascript) to hone in on the items you want. So in this case, the Fetch is going to return some extra results (but will exclude a majority) and then JavaScript will filter the remaining.
Option #2 works great, but is a 2 pass approach.
http://www.meridianworlddata.com/Distance-Calculation.asp
来源:https://stackoverflow.com/questions/11077376/fetchxml-geocode-distance-search-by-distance