10.1: Census Map in InfoWindows

The following sample code has a few differences from last week’s tutorial:

  • It uses a different map service that has a different projection
  • Displays a different chart based on different data
  • Displays the chart in an info-window rather than in the sidebar

Calling a map service that does not have a coordinate system in decimal degrees

In some cases, you may have published a map service that did not have the coordinate system in decimal degrees.  Since Google Maps coordinates are based on decimal degrees, any communication between the two services will need to be translated.  ArcGIS Server provides this translation through their API, simply by providing a few additional parameters in the URL call:

  • inSR=4326&outSR=4326

Here is an example URL call:

1
https://whippet.ats.ucla.edu/ArcGIS/rest/services/apudlin/Car_ownership/MapServer/0/query?geometry='+lng+','+lat+'&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&returnGeometry=true&inSR=4326&outSR=4326&outFields=*&f=pjson&callback=?

Adding an infowindow

First, create an infowindow instance in the global space:

1
2
3
var infowindow = new google.maps.InfoWindow({
    content: '<div id="iw" style="width:450px; height:250px; overflow:hidden;"></div>'
});

Notice that a DIV is created as part of the default content, and given an ID of “iw”. This ID will need to be used in the call to create the charts:

1
var chart = new google.visualization.PieChart(document.getElementById('iw'));

Sample code

(sample code)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>Week 10 - Census Data Infowindow</title>
    <style type="text/css">
        html { height: 100% }
        body { height: 100%; margin: 0px; padding: 0px; font-size:12px;}
        #map_canvas { height: 100% }
        h1 { color:white; }
        .rounded-corners {
            -moz-border-radius: 5px;
            -webkit-border-radius: 5px;
            -khtml-border-radius: 5px;
            border-radius: 5px;
        }
    </style>
 
    <!-- API links -->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="http://yohman.bol.ucla.edu/jquery-1.5.2.min.js"></script>
    <script type="text/javascript" src="http://www.yohman.com/students/rychen88/Scripts/arcgislink.js"></script>  
    <script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.resizable.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>    
    <!-- jQuery UI -->
        <link type="text/css" href="http://www.yohman.com/students/yoh/css/south-street/jquery-ui-1.8.12.custom.css" rel="stylesheet" />   
        <script type="text/javascript" src="http://www.yohman.com/students/yoh/js/jquery-1.5.1.min.js"></script>
        <script type="text/javascript" src="http://www.yohman.com/students/yoh/js/jquery-ui-1.8.12.custom.min.js"></script>
        <script type="text/javascript">
            $(function(){
                // Accordion
                $("#accordion").accordion({ header: "h3",autoHeight: false,collapsible: true, active: false });
                //hover states on the static widgets
                $('#dialog_link, ul#icons li').hover(
                    function() { $(this).addClass('ui-state-hover'); },
                    function() { $(this).removeClass('ui-state-hover'); }
                );
            });
        </script>

    <script type="text/javascript">    

        //load the visualization api
        google.load("visualization", "1", {packages:["corechart"]});
       
        //declare namespace
        var up206b = {};
 
        //declare map
        var map;
       
        //declare geocoder
        var geocoder;
        var geocodemarker;
       
        //infowindow
        var infowindow = new google.maps.InfoWindow();

        //AGS layers       
        var serviceUrlOne = 'https://whippet.ats.ucla.edu/ArcGIS/rest/services/up206b/week9/MapServer';
        var agsMapOne = new gmaps.ags.MapOverlay(serviceUrlOne);



var infowindow = new google.maps.InfoWindow({
    content: '<div id="iw" style="width:450px; height:250px; overflow:hidden;"></div>'
});



        //polygon
        var highlightedpolygon;

        //trace for debugging
        function trace(message)
        {
            if (typeof console != 'undefined')
            {
                console.log(message);
            }
        }
       
        //geocode function
        up206b.geocode = function()
        {
            if (geocodemarker)
            {
                geocodemarker.setMap(null);
            }
           
            var address = $('#address').val();
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK)
                {
                    map.setZoom(13);
                    map.setCenter(results[0].geometry.location);
                    geocodemarker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        animation: google.maps.Animation.DROP,
                        icon: 'http://www.yohman.com/students/yoh/images/down.png'
                    });
                   
                    up206b.getAGSData(results[0].geometry.location.lat(),results[0].geometry.location.lng());
                   
                }
                else
                {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
               
        //toggle single layers on/off
        up206b.toggleLayer = function(layer,id)
        {
            if ($('#'+id).is(':checked'))
            {
                layer.setMap(map);
            }
            else
            {
                layer.setMap(null);
            }
        }
       
        //create a polygon from georss feed coming from AGS
        function createGeoJsonPolygon(geojson){
            //function from http://geojason.info/
            var paths = [];
            $.each(geojson,function(i,n){
                $.each(n,function(j,o){
                    var path=[];
                    $.each(o,function(k,p){
                        var ll = new google.maps.LatLng(p[1],p[0]);
                        path.push(ll);
                    });
                    paths.push(path);
                });
            });
            var polygon = new google.maps.Polygon({
                paths: paths,
                strokeColor: "#00ffff",
                strokeOpacity: 1,
                strokeWeight: 2,
                fillColor: "#46461F",
                fillOpacity: 0.25
            });
            return polygon;
        }
               


        //Get data from ArcGIS Server by lat/lng
        up206b.getAGSData = function(lat,lng)
        {
            //erase existing markers, if any
            if (geocodemarker)
            {
                geocodemarker.setMap(null);
            }
            //erase highlighted polygon, if any
            if (highlightedpolygon)
            {
                highlightedpolygon.setMap(null);
            }
           
            //add a marker
            geocodemarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(lat,lng),
                draggable: true,
                animation: google.maps.Animation.BOUNCE,
                icon: 'http://www.yohman.com/students/yoh/images/down.png'
            });
           
            //infowindow.setContent('hello');
            infowindow.open(map,geocodemarker);
           
            //allow draggable marker to run function again
            google.maps.event.addListener(geocodemarker, 'dragend', function(event) {
                up206b.getAGSData(event.latLng.lat(),event.latLng.lng());
            });

                    //url to AGS map service
            var url = 'https://whippet.ats.ucla.edu/ArcGIS/rest/services/apudlin/Car_ownership/MapServer/0/query?geometry='+lng+','+lat+'&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&returnGeometry=true&inSR=4326&outSR=4326&outFields=*&f=pjson&callback=?';

            $.getJSON(url,function(data)
            {
                trace(data);
                //Highlight the selected polygon
                highlightedpolygon = createGeoJsonPolygon(data.features[0].geometry);
                highlightedpolygon.setMap(map);
               
                var car_vars = ['1_Car','2_or_more','No_Cars'];
                up206b.drawChart(data,car_vars,'car_div','Car Ownership (2000)');
               
            });
        }

        up206b.drawChart = function(agsdata,vars,div_id,title)
        {

            // Create our data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');

            var chartdata = [];

            $.each(agsdata.features[0].attributes,function(item,i)
            {
                if ($.inArray(item,vars) > -1)
                {
                    chartdata.push([item,i]);
                }
            });

            data.addRows(
                chartdata
            );
           
            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById('iw'));
            chart.draw(data, {width: 400, height: 200, title: title});
        }

        //Function that gets run when the document loads
        up206b.initialize = function()
        {
            //set the geocoder
            geocoder = new google.maps.Geocoder();
                       
            var latlng = new google.maps.LatLng(34.0522342, -118.2436849);
            var myOptions = {
                zoom: 13,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
           
            //allow pressing "enter"
            $('#address').keypress(function(e) {
                if(e.which == 13) {
                    up206b.geocode();
                }
            });
           
            agsMapOne.setMap(map);

            google.maps.event.addListener(map, 'click', function(event) {
                up206b.getAGSData(event.latLng.lat(),event.latLng.lng());
            });
           
        }
    </script>
</head>
<body onload="up206b.initialize()">
 
    <!-- side panel div container -->
    <div id="sidepanel" style="position:absolute; width:330px; height: 100%; overflow:auto; float:left; padding-left:10px; padding-right:10px;background:#333">
        <h1>Week 10: Census Data Map - Infowindow version</h1>  
        <div id="accordion">
            <h3><a href="#">Enter an address or just click on the map</a></h3>
            <div>
                <!-- search box -->
                <div style="border:1px solid #ccc; background:#e5e5e5; padding:10px; width:100%;">
                    <span style="width:50px; display: inline-block;">Address:</span>
                    <input type="text" id="address" value="" style="width:100%"> <br>
                    <span style="margin-left:40px; font-size:12px;">Zip, city, or address anywhere in the US!</span>
                </div>
                <div style="border:1px solid #ccc; background:#e5e5e5; padding:10px; width:100%">
                    <input type="checkbox" id="basemap" onClick="up206b.toggleLayer(agsMapOne, 'basemap')" checked>show census tract boundaries
                </div>
            </div>
        </div>
    </div>
    <!-- map div container -->
    <div id="map_canvas" style="height:100%; margin-left:350px;"></div>
</body>  
</html>

Leave a Reply