javascript - Getting Google Maps API geocode to work with full JSON in Rails -
i'm trying google maps api geocode whole json have. have geocode working on show page (this piece of code).
<input id="address" type="hidden" value="<%= @listing.address %>,<%= @listing.city %>,<%= @listing.state %>, <%= @listing.postcode %>"> <div id="showmap"></div> <script> function initmap() { var map = new google.maps.map(document.getelementbyid('showmap'), { zoom: 12, center: {lat: 32.70961, lng: -117.1579991} }); var geocoder = new google.maps.geocoder(); function geocodeme() { geocodeaddress(geocoder, map); }; geocodeme() } function geocodeaddress(geocoder, resultsmap) { var address = document.getelementbyid('address').value; geocoder.geocode({'address': address}, function(results, status) { if (status === 'ok') { resultsmap.setcenter(results[0].geometry.location); var marker = new google.maps.marker({ map: resultsmap, position: results[0].geometry.location }); } else { alert('geocode not successful following reason: ' + status); } }); }
this code have working on index page. shows if hard code lat/long. i'd prefer not doing exercise. instead i'd pull json, geocode it, , have them displayed on google map. here code have working hard code:
<div id="map"></div> <script> document.addeventlistener('domcontentloaded', function () { if (document.queryselectorall('#map').length > 0) { if (document.queryselector('html').lang) lang = document.queryselector('html').lang; else lang = 'en'; var js_file = document.createelement('script'); js_file.type = 'text/javascript'; js_file.src = 'https://maps.googleapis.com/maps/api/js? callback=initmap&signed_in=true&language=' + lang; document.getelementsbytagname('head')[0].appendchild(js_file); } }); var map; function initmap() { map = new google.maps.map(document.getelementbyid('map'), { center: {lat: 33.397, lng: -115.644}, zoom: 8 }); fetch('apartments.json') .then(function(response){return response.json()}) .then(plotmarkers); } var markers; var bounds; function plotmarkers(m) { markers = []; bounds = new google.maps.latlngbounds(); m.foreach(function (marker) { var position = new google.maps.latlng(marker.latitude, marker.longitude); markers.push( new google.maps.marker({ position: position, map: map, animation: google.maps.animation.drop }) ); bounds.extend(position); }); map.fitbounds(bounds); } </script>
any recommendations??
Comments
Post a Comment