Google maps api V3 - Adding multiple markers dynamically from query results

喜欢而已 提交于 2019-12-31 07:31:08

问题


I'm trying to set up a map on a page with a couple of links set up underneath that when clicked, will dynamically query my database and the result set output on the map. I've spent quite a lot of time googling this but can't find quite what I'm looking for. I've got as far as using AJAX to return the lat and lon coordinates OK, but I'm going wrong when trying to create markers on the map, nothing appears though I don't generate any errors.


回答1:


Code not tested, but you can do something like this

Declare map, markers

var map;
var markersArray = [];
var myOptions = {
    zoom: 10,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),  myOptions);

Below function would add a point to map

function plotPoint(srcLat,srcLon,title,popUpContent,markerIcon)
{
    var myLatlng = new google.maps.LatLng(srcLat, srcLon);            
    var marker = new google.maps.Marker({
          position: myLatlng, 
          map: map, 
          title:title,
          icon: markerIcon
      });
    markersArray.push(marker);
    var infowindow = new google.maps.InfoWindow({
        content: popUpContent
    });
      google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });                                          
}

Fetch your points and add them like

var lat = 44.856051;
var lng = -93.242539;
plotPoint(lat,lng,'Mall of America','<span class="gBubble"><b>Mall of America</b><br>60 East Brodway<br>Bloomington, MN 55425</span>');



回答2:


You have this for creating new markers:

var marker = new google.maps.Marker({
    position: results.DATA[i][2],
    map: map,
    title:"New marker"
});
marker.setMap(map);

The value of results.DATA[i][2] is like "54.016893,-0.970721". But the position has to be a LatLng object:

// turn "54.016893,-0.970721" into [54.016893,-0.970721"]
var latLng = results.DATA[i][2].split(",");

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(latLng[0], latLng[1]),
    map: map,
    title:"New marker"
});

PS: Also if you specify the map in the markerOptions, you don't need to also then call the setMap() function.



来源:https://stackoverflow.com/questions/3132464/google-maps-api-v3-adding-multiple-markers-dynamically-from-query-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!