miles haruki
miles haruki

Reputation: 11

How to use Google map.data.loadGeoJson with a JSON string?

I need to load multiple sequential data layers on my Google map. I use a servlet to generate the GeoJSON string, which is retrieved by a XMLHttpRequest. Then I want to load it using map.data.loadGeoJson, but it expects a file as a parameter. I feel that writing the GeoJSON file on the server and then giving the URL as parameter is not efficient.

Is there a way to trick loadGeoJson so it accepts the JSON string from the servlet ? For example, something like :

    xhr = new XMLHttpRequest();
    xhr.open("GET","/hello/MyHello?date="+ d.toISOString(),true);
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) 
        {
            var geoJSON = JSON.parse(this.responseText);
            map.data.loadGeoJson(geoJSON );
        }
    };

Upvotes: 1

Views: 1925

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Don't use loadGeoJson for JSON data, use addGeoJson. loadGeoJson is for "remote" data, if you already have the data, use addGeoJson.

xhr = new XMLHttpRequest();
xhr.open("GET","/hello/MyHello?date="+ d.toISOString(),true);
xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) 
    {
        var geoJSON = JSON.parse(this.responseText);
        map.data.addGeoJson(geoJSON );
    }
};

Upvotes: 2

Related Questions