最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google maps remove labels or grayout area except some regions - Stack Overflow

programmeradmin5浏览0评论

Hi i am using google map and i want your views for the following question.

is it possible to hide or grayout all the area except some other in googlemap?

if Yes, then please give me a hand for this problem.

i have tried but didn't found any solution till now.

here is my FIDDLE DEMO

in that demo i want to grayout/hide labels of all the area with no markers.

here is the sample code which i am using to pin the marker on map.

JS CODE:

<script>
var infowindow;
var map;
var myLatLng = [];

function initialize() {
    var mapOptions = {
        zoom: 3,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    var bounds = new google.maps.LatLngBounds();
    var obj = {
        "JobRecord": [{
            "ApplyUrl": "test",
                "GeoLocations": {
                "GeoLocationRecord": [{
                    "Latitude": "21.543333",
                        "Longitude": "39.172777"
                }, {
                    "Latitude": "21.299135",
                        "Longitude": "40.428313"
                }]
            },
                "JobId": "493743",
                "JobTitle": "Sales Associate",
                "Locations": {
                "LocationRecord": [{
                    "Group": "Saudi Arabia",
                        "Title": "Taif"
                }, {
                    "Group": "Saudi Arabia",
                        "Title": "Jeddah"
                }]
            }
        }, {
            "ApplyUrl": "test",
                "GeoLocations": {
                "GeoLocationRecord": {
                    "Latitude": "55.755826",
                        "Longitude": "37.617300"
                }
            },
                "JobId": "492725",
                "JobTitle": "Business Director - Starbucks - Russia",
                "Locations": {
                "LocationRecord": {
                    "Group": "Russia",
                        "Title": "Moscow"
                }
            }
        }, {
            "ApplyUrl": "test",
                "GeoLocations": {
                "GeoLocationRecord": {
                    "Latitude": "25.271139",
                        "Longitude": "55.307485"
                }
            },
                "JobId": "492730",
                "JobTitle": "Vice President - Victoria's Secret",
                "Locations": {
                "LocationRecord": {
                    "Group": "UAE",
                        "Title": "Dubai"
                }
            }
        }]
    };
    var jobs = obj.JobRecord;
    for (var i = 0; i < jobs.length; i++) {
        if (jobs[i].GeoLocations.length != 0) {
            var geoLocationRecord = jobs[i].GeoLocations.GeoLocationRecord;
            var myjobs = new Array();

            var single = new Object();

            if (geoLocationRecord.length === undefined) {

                single.JobId = jobs[i].JobId;
                single.JobTitle = jobs[i].JobTitle;
                single.Locations = jobs[i].Locations.LocationRecord;

                var search = [geoLocationRecord.Latitude, geoLocationRecord.Longitude, single];
                isLocationFree(search);
            } else {
                for (var j = 0; j < geoLocationRecord.length; j++) {
                    single[j] = new Object();

                    single[j].JobId = jobs[i].JobId;
                    single[j].JobTitle = jobs[i].JobTitle;
                    single[j].Locations = jobs[i].Locations.LocationRecord[j];

                    var search = [geoLocationRecord[j].Latitude, geoLocationRecord[j].Longitude, single[j]];
                    isLocationFree(search);
                } //finish inner loop
            }
        } //finish if condition
    } //finish loop

    for (var x = 0; x < myLatLng.length; x++) {
        var latlng = new google.maps.LatLng(parseFloat(myLatLng[x][0]),
        parseFloat(myLatLng[x][1]));
        bounds.extend(latlng);

        createMarker(myLatLng[x], latlng);
    }
    map.fitBounds(bounds);
    var listener = google.maps.event.addListener(map, "idle", function () {
        if (map.getZoom() > 16) map.setZoom(3);
        google.maps.event.removeListener(listener);
    });
}

function createMarker(jobs, latlng) {
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });

    google.maps.event.addListener(marker, "click", function () {
        if (infowindow) infowindow.close();
        infowindow = new google.maps.InfoWindow({
            content: createMessage(jobs)
        });
        infowindow.open(map, marker);
    });
    return marker;
}

function createMessage(jobs) {
    console.log(jobs);
    console.log("Total==>" + (Number(jobs.length) - 2));

    if (jobs[2].Locations !== undefined) {
        var locationTitle = jobs[2].Locations.Title;
    } else {
        var locationTitle = "";
    }

    var message = '';
    message += '<div id="popupContent">' +
        '<strong id="firstHeading" class="firstHeading">' + (Number(jobs.length) - 2) + " Vacancies in " + locationTitle + '</strong>' +
        '<br><br>';
    for (var y = 2; y < jobs.length; y++) {
        message += '<a href="/' + jobs[y].JobId + '" target="_blank">' + jobs[y].JobTitle + '</a><br>';

    }
    message += '</div>';

    return message;
}

function isLocationFree(search) {
    for (var i = 0; i < myLatLng.length; i++) {
        if (myLatLng[i][0] === search[0] && myLatLng[i][1] === search[1]) {
            myLatLng[i].push(search[2]);
            return true;
        }
    }
    myLatLng.push(search);
    return myLatLng;
}
$(document).ready(function () {
    initialize();
});
</script>

Hi i am using google map and i want your views for the following question.

is it possible to hide or grayout all the area except some other in googlemap?

if Yes, then please give me a hand for this problem.

i have tried but didn't found any solution till now.

here is my FIDDLE DEMO

in that demo i want to grayout/hide labels of all the area with no markers.

here is the sample code which i am using to pin the marker on map.

JS CODE:

<script>
var infowindow;
var map;
var myLatLng = [];

function initialize() {
    var mapOptions = {
        zoom: 3,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    var bounds = new google.maps.LatLngBounds();
    var obj = {
        "JobRecord": [{
            "ApplyUrl": "test",
                "GeoLocations": {
                "GeoLocationRecord": [{
                    "Latitude": "21.543333",
                        "Longitude": "39.172777"
                }, {
                    "Latitude": "21.299135",
                        "Longitude": "40.428313"
                }]
            },
                "JobId": "493743",
                "JobTitle": "Sales Associate",
                "Locations": {
                "LocationRecord": [{
                    "Group": "Saudi Arabia",
                        "Title": "Taif"
                }, {
                    "Group": "Saudi Arabia",
                        "Title": "Jeddah"
                }]
            }
        }, {
            "ApplyUrl": "test",
                "GeoLocations": {
                "GeoLocationRecord": {
                    "Latitude": "55.755826",
                        "Longitude": "37.617300"
                }
            },
                "JobId": "492725",
                "JobTitle": "Business Director - Starbucks - Russia",
                "Locations": {
                "LocationRecord": {
                    "Group": "Russia",
                        "Title": "Moscow"
                }
            }
        }, {
            "ApplyUrl": "test",
                "GeoLocations": {
                "GeoLocationRecord": {
                    "Latitude": "25.271139",
                        "Longitude": "55.307485"
                }
            },
                "JobId": "492730",
                "JobTitle": "Vice President - Victoria's Secret",
                "Locations": {
                "LocationRecord": {
                    "Group": "UAE",
                        "Title": "Dubai"
                }
            }
        }]
    };
    var jobs = obj.JobRecord;
    for (var i = 0; i < jobs.length; i++) {
        if (jobs[i].GeoLocations.length != 0) {
            var geoLocationRecord = jobs[i].GeoLocations.GeoLocationRecord;
            var myjobs = new Array();

            var single = new Object();

            if (geoLocationRecord.length === undefined) {

                single.JobId = jobs[i].JobId;
                single.JobTitle = jobs[i].JobTitle;
                single.Locations = jobs[i].Locations.LocationRecord;

                var search = [geoLocationRecord.Latitude, geoLocationRecord.Longitude, single];
                isLocationFree(search);
            } else {
                for (var j = 0; j < geoLocationRecord.length; j++) {
                    single[j] = new Object();

                    single[j].JobId = jobs[i].JobId;
                    single[j].JobTitle = jobs[i].JobTitle;
                    single[j].Locations = jobs[i].Locations.LocationRecord[j];

                    var search = [geoLocationRecord[j].Latitude, geoLocationRecord[j].Longitude, single[j]];
                    isLocationFree(search);
                } //finish inner loop
            }
        } //finish if condition
    } //finish loop

    for (var x = 0; x < myLatLng.length; x++) {
        var latlng = new google.maps.LatLng(parseFloat(myLatLng[x][0]),
        parseFloat(myLatLng[x][1]));
        bounds.extend(latlng);

        createMarker(myLatLng[x], latlng);
    }
    map.fitBounds(bounds);
    var listener = google.maps.event.addListener(map, "idle", function () {
        if (map.getZoom() > 16) map.setZoom(3);
        google.maps.event.removeListener(listener);
    });
}

function createMarker(jobs, latlng) {
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });

    google.maps.event.addListener(marker, "click", function () {
        if (infowindow) infowindow.close();
        infowindow = new google.maps.InfoWindow({
            content: createMessage(jobs)
        });
        infowindow.open(map, marker);
    });
    return marker;
}

function createMessage(jobs) {
    console.log(jobs);
    console.log("Total==>" + (Number(jobs.length) - 2));

    if (jobs[2].Locations !== undefined) {
        var locationTitle = jobs[2].Locations.Title;
    } else {
        var locationTitle = "";
    }

    var message = '';
    message += '<div id="popupContent">' +
        '<strong id="firstHeading" class="firstHeading">' + (Number(jobs.length) - 2) + " Vacancies in " + locationTitle + '</strong>' +
        '<br><br>';
    for (var y = 2; y < jobs.length; y++) {
        message += '<a href="http://jobsearch.alshaya./cau/en/job/' + jobs[y].JobId + '" target="_blank">' + jobs[y].JobTitle + '</a><br>';

    }
    message += '</div>';

    return message;
}

function isLocationFree(search) {
    for (var i = 0; i < myLatLng.length; i++) {
        if (myLatLng[i][0] === search[0] && myLatLng[i][1] === search[1]) {
            myLatLng[i].push(search[2]);
            return true;
        }
    }
    myLatLng.push(search);
    return myLatLng;
}
$(document).ready(function () {
    initialize();
});
</script>
Share Improve this question asked Jan 24, 2014 at 9:04 Dhaval BharadvaDhaval Bharadva 3,0832 gold badges25 silver badges36 bronze badges 7
  • Possible duplicate of stackoverflow./questions/12591937/… – MrUpsidown Commented Jan 24, 2014 at 9:21
  • You can also check this: gis.stackexchange./questions/18867/… but I find these examples/solutions a bit clumsy. – MrUpsidown Commented Jan 24, 2014 at 9:25
  • In any case, I think you will need geometry data. KML Layer seems to be the best option to me. – MrUpsidown Commented Jan 24, 2014 at 9:27
  • @MrUpsidown how can i implement KML Layer with my current code.? – Dhaval Bharadva Commented Jan 24, 2014 at 9:33
  • Check the example provided by @Geocodezip in my first link. You can check the code and the links to the doc. Also you can check this answer for a local version of the geometry data: stackoverflow./questions/21302002/google-map-as-a-vector-map/… You need to find the right geometry dataset. What do you want to hide? You mentioned greyout all the area and greyout labels. You can greyout/hide road labels and other features for the whole map, not for a specific region/country. You can greyout an area with a polygon, based on geometry data. – MrUpsidown Commented Jan 24, 2014 at 9:44
 |  Show 2 more ments

3 Answers 3

Reset to default 5 +50

You can do that quite easily by using a Fusion Table Layer.

I consider here the mentioned "area" or "regions" as countries - I guess you simply want to gray out the countries that is not present in your XML-feed?

Here I have hardcoded the countries from your example - Russia, Saudia Arabia and United Arab Emirates. You must yourself create the logic to exclude the countries you meet in your feed.

function greyoutWorld() {
    var world_geometry = new google.maps.FusionTablesLayer({
        query: {
            select: 'geometry',
            from: '1N2LBk4JHwWpOY4d9fobIn27lfnZ5MDy-NoqqRpk',
            //select all but russia, saudi arabia and united arab emirates
            where: "ISO_2DIGIT NOT IN ('RU', 'SA', 'AE')"
        },
        //add some grey color to cover the rest of the world
        styles: [{
            polygonOptions: {
                fillColor: "#dadada",
                strokeColor: "#ebebeb",
                strokeWeight: "int"
            },
            polylineOptions: {
                strokeColor: "#rrggbb",
                strokeWeight: "int"  
            }
        }],
        map: map,
        suppressInfoWindows: true
    });
}

The result looks like this :

Forked fiddle -> http://jsfiddle/QUPdZ/


Update

Regarding the "red circle markers", this feature is built into the Fusion Table layer code, and cannot be suppressed. See the documentation, under "Limits" :

When looking at the map, you may notice:
* The ten largest-area ponents of a multi-geometry are shown.
* When zoomed farther out, tables with more than 500 features will show dots (not lines or polygons).

The workaround is to add

minZoom: 2

to the map options, like in this fiddle -> http://jsfiddle/LVRp2/

The country geometry Fusion Table - World Country Boundaries.kml - is public and accessible here :

https://www.google./fusiontables/DataSource?docid=1N2LBk4JHwWpOY4d9fobIn27lfnZ5MDy-NoqqRpk.

An alternative, same source I guess - World Country Boundaries.csv - can be found here :

https://www.google./fusiontables/DataSource?docid=1uL8KJV0bMb7A8-SkrIe0ko2DMtSypHX52DatEE4.

Both works with the above fiddle.

I have achieved this in v2 of googlemaps by overlaying a shape overlay (i.e. a polygon that enpasses the whole world BUT the area I want shown).

In the end my area was fairly plex so I ended up generating it with google maps and saving the shape in a separate .kmz file, you will be able to achieve the result both ways.

Here is a fiddle of adding the perimeter one coordinate pair at a time.

The KmlLayer function allows you to load a .kmz you have generated from google map; see also this answer on Stackoverflow: Using KMZ Files in Google Maps

In google maps, follow this tutorial to generate the kml

Let's make a recap here.

While you have a few solutions explained here, they all require external data that btw. is hard to maintain and inplete (I still could not find a Fusion Table world boundaries dataset that is plete).

I personnaly don't think this is a good way of "highlighting" where the positions are, and I think this is overplicated.

Another possibility would be to use a marker clusterer which is very good to highlight where most of your positions are. And it's easy to implement.

What we don't know is what features you need from the Google Maps API. Maybe you should consider using another service that might allow easier manipulation of boundaries data. Did you already check jVectorMap for instance?

I know my answer is not really a solution to your question, but it might help you ask yourself the right question: Is greying out some areas on the map the best option to highlight where the positions are?

发布评论

评论列表(0)

  1. 暂无评论