Google Maps API: Create a store locator

后端 未结 4 507
暗喜
暗喜 2021-02-06 17:41

Today I am trying to make a store locator using google maps\' api. The store locator is to be set up like so: two areas, one with a map containing all the stores in a given area

4条回答
  •  悲&欢浪女
    2021-02-06 18:18

    I'm creating a new answer, since my other answer is getting messy.

    In order to get proper closure, you'll need to create a separate function to make the geocoder request. The following code will allow you to assign the desired infoWindow text to each marker.

    for(var i = 0; i < locations.length; i++) {
        var address = locations[i]['address'] + ', ' + locations[i]['city'] + ' ' + locations[i]['state'] + ', ' + locations[i]['zip_code'];
        var text = locations[i]['address']; // or whatever you want the text to be
        getLocation(address, text);
    }
    

    ...

    function getLocation(address, text) {
        geocoder.getLocations(address, function(response) {
            var place = response.Placemark[0];
            var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
            marker = new GMarker(point);
            marker.bindInfoWindowHtml(text); // note that if you want to use GEvent.addListener() instead - you'll need to create another function to get proper closure
            map.addOverlay(marker);
        });
    }
    

    For more info on closure in Google maps, see these questions:

    • One
    • Two
    • Three

提交回复
热议问题