如何使用arcgis javascript api将结果附加到Geocoder文本框中

How to append result to Geocoder text box using arcgis javascript api?

本文关键字:Geocoder 文本 结果 arcgis 何使用 javascript api      更新时间:2023-09-26

我想在arcgis javascript api的Geocoder文本框中添加自定义搜索的结果,方法是去掉默认结果。

我已经写了下面的代码,但我没有得到满意的结果。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Geocoder</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<style>
    html, body, #map
    {
        height: 100%;
        width: 100%;
        margin: 0;
        padding: 0;
    }
    #search
    {
        display: block;
        position: absolute;
        z-index: 3;
        top: 20px;
        left: 75px;
    }
    .spotlight
    {
        z-index: -1;
        position: absolute;
        left: 50%;
        top: 50%;
        border-radius: 50%;
        opacity: 0;
        box-shadow: inset rgba(0,0,0,0.25) 0px 0px 20px 20px, rgba(0,0,0,0.25) 0px 0px 0px 1000px;
        transition: all 1000ms;
        -moz-transition: all 1000ms;
        -webkit-transition: all 1000ms;
    }
    .spotlight-active
    {
        z-index: 2;
        opacity: 1;
    }
</style>
<script src="http://js.arcgis.com/3.11/"></script>
<script type="text/javascript">
    require([
    "esri/map",
    "esri/dijit/Geocoder",
    "esri/graphic",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/geometry/screenUtils",
    "dojo/dom",
    "dojo/dom-construct",
    "dojo/query",
    "dojo/_base/Color",
    "esri/tasks/locator",
    "esri/geometry/Polygon",
    "dojo/_base/array",
    "dojo/domReady!"
    ], function (
    Map, Geocoder,
    Graphic, SimpleMarkerSymbol, screenUtils,
    dom, domConstruct, query, Color, Locator, Polygon, arrayUtils
  ) {
        var _RLCCspatialReference = new esri.SpatialReference({ "wkt": 'classified' });
        //var _RMapsExt = new esri.geometry.Extent(-4086033.961945721, -806460.9357572012, 3756052.906228016, 5050597.693910059, _RLCCspatialReference);
        var _RMapsExt = new esri.geometry.Extent(-2498256.744659858, 887180.8538370342, 2243086.071359108, 4139445.6917000436, _RLCCspatialReference);
        // create a map and instance of the geocoder widget here
        var map = new esri.Map("map", { logo: false, nav: false, wrapAround180: true });
        map.spatialReference = _RLCCspatialReference;
        map.fullExtent = _RMapsExt;
        map.initialExtent = _RMapsExt;
        var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://xxxx.rxx.com/arcgis/rest/services/Rmaps_Updated/MapServer");
        map.addLayer(tiledMapServiceLayer);
        map.setScale(14000000);
        map.setExtent(_RMapsExt, true);
        var gc = [{
            url: "http://11.66.22.33:6080/arcgis/rest/services/Locator_Comb_Prd/GeocodeServer",
            name: "Locator_Comb_Prd",
            singleLineFieldName: "SingleLine"
        }];
        var geocoder = new Geocoder({
            map: map,
            arcgisGeocoder: false,
            geocoders: gc,
            autoNavigate: false,
            autoComplete: true,
            showResults: true,
            geocoders: gc,
            geocoderMenu: false,
        }, dom.byId("search"));
        //"search" dom.byId("search")
        geocoder.startup();
        geocoder.on("select", showLocation);
        geocoder.on("FindResults", showLocation);
        dojo.connect(geocoder, 'onAutoComplete', function (results) {
            $("#search_input").autocomplete({
                source: function (request, response) {
                    $.support.cors = true;
                    $.ajax({
                        dataType: "json",
                        type: 'POST',
                        url: 'http://11.66.22.44/Geocoder/Query.aspx',
                        crossdomain: true,
                        timeout: 100000,
                        cache: true,
                        data: { RequestType: "AutoComplete", AutoCompleteValue: $("#search_input").val() },
                        success: function (data) {
                            //$('input.suggest-user').removeClass('ui-autocomplete-loading');  // hide loading image
                            if (data != null) {
                                response(data);
                            }
                        },
                        error: function (data) {
                            alert("error:" + data.statusText);
                            //$('input.suggest-user').removeClass('ui-autocomplete-loading');
                        }
                    });
                },
                minLength: 3,
                open: function () {
                },
                close: function () {
                },
                focus: function (event, ui) {
                },
                select: function (event, ui) {
                }
            });
            //console.log('autocomplete', results);
        });
        function showLocation(evt) {
            var point = null;
            if (evt.result.feature.geometry.type == "point" && evt.result.feature.geometry.x != 0 && evt.result.feature.geometry.y != 0) {
                point = evt.result.feature.geometry;
                map.graphics.clear();
                var symbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_SQUARE).setColor(new Color([255, 0, 0, 0.5]));
                var graphic = new Graphic(point, symbol);
                map.graphics.add(graphic);
                map.infoWindow.setTitle("Search Result");
                map.infoWindow.setContent(evt.result.name);
                map.infoWindow.show(evt.result.feature.geometry);
            }
            else {
                map.graphics.clear();
                locator = new Locator("http://11.66.66.33:6080/arcgis/rest/services/Locator_Comb_Prd/GeocodeServer");
                locator.on("address-to-locations-complete", showResults);
                var address = {
                    "SingleLine": evt.result.name
                };
                var resultName = evt.result.name;
                locator.outSpatialReference = map.spatialReference;
                var options = {
                    address: address,
                    outFields: ["Loc_name"]
                };
                locator.addressToLocations(options);
                function showResults(evt) {
                    var symbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_SQUARE).setColor(new Color([255, 0, 0, 0.5]));

                    var geom;
                    arrayUtils.every(evt.addresses, function (candidate) {
                        if (candidate.location.type == "point" && candidate.location.x != 0 && candidate.location.y != 0) {
                            console.log(candidate.score);
                            if (candidate.score > 80) {
                                console.log(candidate.location);
                                var attributes = {
                                    address: candidate.address,
                                    score: candidate.score,
                                    locatorName: candidate.attributes.Loc_name
                                };
                                geom = candidate.location;
                                point = geom;
                                var graphic = new Graphic(point, symbol);
                                //add a graphic to the map at the geocoded location
                                map.graphics.add(graphic);
                                //add a text symbol to the map listing the location of the matched address.

                                map.infoWindow.setTitle("Search Result");
                                map.infoWindow.setContent(resultName);
                                map.infoWindow.show(point);
                                return false; //break out of loop after one candidate with score greater  than 80 is found.
                            }
                        }
                        else {
                            var polygonGeom = new Polygon(candidate.location.spatialReference);
                            polygonGeom.addRing(candidate.location.rings[0]);
                            geom = polygonGeom.getCentroid();
                            point = geom;
                            console.log(candidate.score);
                            if (candidate.score > 80) {
                                console.log(candidate.location);
                                var attributes = {
                                    address: candidate.address,
                                    score: candidate.score,
                                    locatorName: candidate.attributes.Loc_name
                                };

                                point = geom;
                                var graphic = new Graphic(point, symbol);
                                //add a graphic to the map at the geocoded location
                                map.graphics.add(graphic);
                                //add a text symbol to the map listing the location of the matched address.
                                map.infoWindow.setTitle("Search Result");
                                map.infoWindow.setContent(resultName);
                                map.infoWindow.show(point);
                                return false; //break out of loop after one candidate with score greater  than 80 is found.
                            }
                        }
                    });

                    if (geom !== undefined) {
                        map.centerAndZoom(geom, 14);
                    }
                }
            }
            if (point != undefined || point != null) {
                map.centerAndZoom(point, 14);
            }

        }
    });        
</script>
<script type="text/javascript">
    $(function () {
        $("#map").css("height", $(window).height());
        $("#map").css("width", $(window).width());
        //map_root
        $("#map_root").css("height", $(window).height());
        $("#map_root").css("height", $(window).width());
    });
</script>
</head>
 <body>
    <form id="form1" runat="server">
        <div id="search">
        </div>
        <div id="map" style="width: 100%; height: 100%;">
       </div>        
      </form>
 </body>
</html>

有什么建议吗?

是的,我找到了这个问题的解决方案,基本上我可以使用Jquery附加我收到的数据。

毕竟它只是一个HTML!

但是仍然可以有一个更好的解决方案,请一定要发布它。

$.ajax({
                        dataType: "json",
                        type: 'POST',
                        //url: 'http://11.66.22.44/Geocoder/Query.aspx',
                        url: 'Query.aspx',
                        //crossdomain: true,
                        timeout: 500000,
                        cache: true,
                        data: { RequestType: "AutoComplete", AutoCompleteValue: $("#search_input").val() },
                        success: function (data) {
                            //$('input.suggest-user').removeClass('ui-autocomplete-loading');  // hide loading image
                            var actualLength = $(".esriGeocoderResults ul").length;
                            if (data != null) {
                                //response(data); 
                                if ($(".esriGeocoderResults ul").length == 0) {
                                    $(".esriGeocoderResults").append('<ul role="presentation">');
                                }
                                if ($("#search").hasClass("esriGeocoderResultsOpen") == false) {
                                    $("#search").addClass("esriGeocoderResultsOpen");
                                }
                                $(".esriGeocoderResults").css("display", "block");
                                for (var index = 0; index < data.length; index++) {
                                    if ($(".esriGeocoderResults ul").text().indexOf(data[index]) == -1) {
                                        if (actualLength % 2 == 0) {
                                            $(".esriGeocoderResults ul").append('<li onClick = "locatorClick(this);" class="esriGeocoderResult esriGeocoderResultEven" title="' + data[index] + '" role="menuitem" tabindex="0" data-index="' + (actualLength) + '" data-item="true" data-text="' + data[index] + '">' + data[index] + '</li>');
                                            actualLength++;
                                        }
                                        else {
                                            $(".esriGeocoderResults ul").append('<li onClick = "locatorClick(this);" class="esriGeocoderResult esriGeocoderResultOdd" title="' + data[index] + '" role="menuitem" tabindex="0" data-index="' + (actualLength) + '" data-item="true" data-text="' + data[index] + '">' + data[index] + '</li>');
                                            actualLength++;
                                        }
                                    }
                                }
                                $(".esriGeocoderResults ul").bind();
                                //alert($(".esriGeocoderResults ul").length);
                                //$(".esriGeocoderResults ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
                            }
                        },
                        error: function (data) {
                            alert("error:" + data.statusText);
                            //$('input.suggest-user').removeClass('ui-autocomplete-loading');
                        }
                    });