简体   繁体   中英

Initializing google maps with multiple markers from an array

I'm passing 2 arrays into google maps, one for a location (which is geocoded) and another for that location's info window.

Is there any way I can initialize the map and plot all these points at once, or will I have to make a second function to plot more points? Since there are multiple points, I'm not sure how else to do it other than plotting one point, and then making an addition function which loops through the array and plots the rest.

Here's the code.

The two arrays(which I didn't include the code for) are $cityArray and $title

function initialize() {
        geocoder = new google.maps.Geocoder();
        latlang = geocoder.geocode( { 'address': 
                                    '<?php echo json_encode($cityArray); ?>'}, 
                                       function(results, status) { 
        //use latlang to enter city instead of coordinates 
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
               google.maps.event.addListener(marker, 'click', 
                                             (function(marker, i) {
                return function() {
                    infowindow.setContent(
                        '<?php echo json_encode($title); ?>'
                    );
                    infowindow.open(map, marker);
                }
            })(marker, i));
            markersArray.push(marker);
        }
        else{
            alert("Geocode was not successful for the following reason: " 
                  + status);
        }
    });
    var myOptions = {
        center: latlang, zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };

    var gm = google.maps;
    map = new google.maps.Map(document.getElementById("main_Content"), 
                              myOptions);
    plotMarkers();

} //end of initialization function

var infowindow = new google.maps.InfoWindow();

Please refer the following Sample which i have used for the above.,

Step1 : Include the Three script Files in header of your page.,like

(i). <scrip type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<scrip type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<scrip type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>

Step2 : Scripts On Page

<script type="text/javascript">

//initialize the map window

jQuery(document).ready(function () {
    load();
});

jQuery(window).unload(function () {
    GUnload();
});

    var map;
    var geocoder;
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();

    function load() {
        if (GBrowserIsCompatible()) {
            geocoder = new GClientGeocoder();
            map = new GMap2(document.getElementById('map'));
            map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl());
            //map.setCenter(new GLatLng(35.048629,-0.820663), 4);
            searchLocations();
            document.getElementById('directions-panel').innerHTML = '';
            var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
            var print_icon_url_new = '<a href="javascript:void(0);" class="print" onClick="window.open(\'' + url_new + '\');">Print</a><a href="#" class="link">Link</a>';
            jQuery('#print_icon').html(print_icon_url_new);
        }
    }


//Search Locations with address input

 function searchLocations() {

        var address = document.getElementById('addressInput').value;
        // alert(address);
        var address_new = jQuery("#addressInput_new").val();
        if (address_new != "Enter City or Zip") {
            jQuery("#loc1").html(address_new);
        }
        geocoder.getLatLng(address, function (latlng) {
            //alert(latlng);
            if (!latlng) {
                alert(address + ' not found');
            } else {
                searchLocationsNear(latlng);
            }
        });

    }


// Search Near By Location to place the Markers and Information windows

function searchLocationsNear(center) {
        var radius = document.getElementById('radiusSelect').value;
        var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';


        jQuery.get(searchUrl, function (data) {

            var xml = GXml.parse(data);


            var markers = xml.documentElement.getElementsByTagName('marker');
            map.clearOverlays();

            var sidebar = document.getElementById('sidebar');
            var sidebar_val = '';
            //sidebar.innerHTML = 'Results Found';
            jQuery("#sidebar").html(sidebar_val);

            <!--jQuery("#loc_count").html(markers.length);-->


            if (markers.length == 0) {
                sidebar.innerHTML = 'No results found.';
                map.setCenter(new GLatLng(35.048629, -0.820663), 4);
                return;
            }

            var bounds = new GLatLngBounds();
            for (var i = 0; i < markers.length; i++) {
                var name = markers[i].getAttribute('name');
                var address = markers[i].getAttribute('address');
                var phone_new = markers[i].getAttribute('phonenumber');
                var distance = parseFloat(markers[i].getAttribute('distance'));
                var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
                var markerchar = "b";
                var marker = createMarker(point, name, address, phone_new);
                map.addOverlay(marker);
                // var location_count = jQuery('#loc_count').val();
                jQuery('#loc_count').val(i + 1);

                var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);

                jQuery('#sidebar').append(sidebarEntry);


                //sidebar.appendChild(sidebarEntry);

                //  ScrollPane.getContentPane().appendChild(sidebarEntry);
                bounds.extend(point);

            }
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
            jQuery('#sidebar').jScrollPane();
            //jQuery('#sidebar').reinitialise();

        });

    }

//To Create a Marker With Information Window

 function createMarker(point, name, address, phone_new) {

        var pinkIcon = new GIcon(G_DEFAULT_ICON);
        pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
        var markerOptions = {
            icon: pinkIcon
        };


        var marker = new GMarker(point, markerOptions);
        var event_calendar = "event_calendar";
        var event_title = ""+ benObj.event_title +"";
        var display = "block";
        var e_dt_start = jQuery("#dtstart").val();
        var e_dt_end = jQuery("#dtend").val();
        var e_start_timestamp = (formatTimestring(e_dt_start));
        var e_end_timestamp = (formatTimestring(e_dt_end));
        var e_desc = jQuery("#edesc").val();
        var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
        var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
        var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br><a href="javascript:void(0);" style="text-decoration:none;" onclick="addtocalender();" class="addtocal" id="add_to_cal">Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div></a>&nbsp;|&nbsp;<a href="javascript:void(0);" style="text-decoration:none;">Remind Me</a><br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;">&nbsp;<input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
        GEvent.addListener(marker, 'click', function () {
            marker.openInfoWindowHtml(html);

            //jQuery(this).addtocal();
        });
        return marker;
    }

// To Make Sidebar Entry If need

 function createSidebarEntry(marker, name, address, distance, phone_new) {
        var div = document.createElement('div');
        var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' &ndash; '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am &ndash; 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';

        div.innerHTML = html;
        div.style.cursor = 'pointer';
        div.style.marginBottom = '5px';
        GEvent.addDomListener(div, 'click', function () {
            GEvent.trigger(marker, 'click');
        });
        GEvent.addDomListener(div, 'mouseover', function () {
            div.style.backgroundColor = '#eee';
        });
        GEvent.addDomListener(div, 'mouseout', function () {
            div.style.backgroundColor = '#fff';
        });
        return div;
    }

// To make a Directions If need

function calcRoute() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
        var print_icon_url = '<a href="javascript:void(0);" class="print" onClick="window.open(\'' + url + '\');">Print</a><a href="#" class="link">Link</a>';

        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var myOptions = {
                    zoom: 7,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: new google.maps.LatLng(41.850033, -87.6500523)
                };
                map = new google.maps.Map(document.getElementById('map'), myOptions);
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById('directions-panel'));
                directionsDisplay.setDirections(response);
                jQuery('#print_icon').html(print_icon_url);
            }
        });
    }

</script>

//To Create a XML For Markers and Information Windows

<?php
function mapMarker($center_lat,$center_lng,$radius)
    {
    $mysqli = $this->_getMySqlConnection();
    // Start XML file, create parent node
    $dom        =   new DOMDocument("1.0");
    $node       =   $dom->createElement("markers");
    $parnode    =   $dom->appendChild($node);

    // Search the rows in the markers table
    $query      =   sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
    $mysqli->real_escape_string($center_lat),
    $mysqli->real_escape_string($center_lng),
    $mysqli->real_escape_string($center_lat),
    $mysqli->real_escape_string($radius));

    $result = $mysqli->query($query);

    header("Content-type: text/xml");
    header('Access-Control-Allow-Origin: *');

    $avoid_duplicate="";
    // Iterate through the rows, adding XML nodes for each
        while ($row = @$result->fetch_assoc())
        {
            if($avoid_duplicate!=$row['store_name'])
            {
            $node = $dom->createElement("marker");
            $newnode = $parnode->appendChild($node);
            $newnode->setAttribute("name", $row['store_name']);
            $newnode->setAttribute("address", $row['street_address_1']);
            $newnode->setAttribute("lat", $row['lat']);
            $newnode->setAttribute("lng", $row['lng']);
            $newnode->setAttribute("distance", $row['distance']);
            $newnode->setAttribute("phonenumber", $row['phone']);
            $avoid_duplicate=$row['store_name'];
            }
        }

    $outXML=$dom->saveXML();
    $result->close();           
    $mysqli->close();
    return $outXML;
    }
?>

HTML Part :

<div class="mapleft">
   <div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
   <div class="mapshadow"></div>
</div>
    <input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
    <input type="hidden" id="radiusSelect" value="50" />
    <input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
    <input type="hidden" id="radiusSelect_temp" value="50" />
    <input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />

These are the things which will produce the great out comes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM