Dynamically add V3 markers to Google Map using jQuery

I am adding markers to Google Maps dynamically using jQuery and the Google Maps V3 API. When the search_button button is clicked, the request is sent to the server using AJAX, which returns a LatLng JSON array corresponding to the results that will be used to place the markers. However, in my Javascript Conole, I get the error message: Invalid value for property <map>: map . Where am I wrong? Here is my code:

JS HTML Header:

 <script type="text/javascript"> function initialize() { var latlng = new google.maps.LatLng(42.354183,-71.065063); var options = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), options); } </script> 

JQuery

 $(function() { $("#search_button").click(function(e){ e.preventDefault(); // Place markers on map for( i = 0; i < json.length; i++) { var latLng = new google.maps.LatLng(json[i].lat, json[i].lng); var marker = new google.maps.Marker({ position: latLng, map: map }); } }); }); }); 
+6
source share
1 answer

you must make a global variable called map. That's all, actually my recommendation is to move everything to a javascript file like this

  $(document).ready(initialize); var map; function initialize() { var latlng = new google.maps.LatLng(42.354183,-71.065063); var options = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map($('#map-canvas')[0], options); $("#search_button").click(function(e){ e.preventDefault(); // Place markers on map for( i = 0; i < json.length; i++) { var latLng = new google.maps.LatLng(json[i].lat, json[i].lng); var marker = new google.maps.Marker({ position: latLng, map: map }); } }); } 
+20
source

Source: https://habr.com/ru/post/899753/


All Articles