I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
You Should define your variables queryLat and queryLng globally where your script starts.
<script type="text/javascript">
var queryLat;
var queryLng;
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
The problem is in this code:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
You have enclosed the string with apostrophes, but the string contains apostrophes too.
Use this instead:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"
Related
I have rendered a map with markers, which are saved as long lat values in a local xlsx file.
My aim is to automatically zoom to all markers, which are loaded via an input file button. For this I am using the fitbounds() method from googlemaps API.
Partial Example
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//create global infoWindow object
var infoWindow = new google.maps.InfoWindow();
var i, newMarker;
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
}
}
};
reader.readAsArrayBuffer(f);
}
But if I run my html file, it zooms just to one marker. I suppose that it is the first marker of the gmarkers array.
However I want to achieve following result, with the full extent of my uploaded marker:
In my main.html you can see my initMap() function and the function which is called if the document is ready. In the document ready function the handlefunction () is called.
var map;
//Change event to dropdownlist
$(document).ready(function(){
a = $('#input-id').fileinput({
'showUpload': false,
'showPreview': false,
'showCaption': false
});
a.change(handleFile);
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.7758459, lng: 9.1829321},
zoom: 3,
mapTypeControl: false
});
}
You have a typo in your code. Move the initialization of the bounds outside the loop.
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
should be:
bounds = new google.maps.LatLngBounds();
for (var i=0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
proof of concept fiddle
code snippet:
var result = [{
Latitude: 37.4419,
Longitude: -122.1419
}, {
Latitude: 37.44,
Longitude: -122.14
}, {
Latitude: 40.44,
Longitude: -75.14
}]
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
This is another approach for your problem within 35 lines of code.
Make sure you pass the JSON object the right way and that you declare your classes within the appropriate lexical scope.
Make sure the JSON Object returns something like this:
const coords = [
{lat: 42.4, lng: 1.55},
{lat: 43.42, lng: 2.48},
{lat: 45.43, lng: 4.9}
];
Note I have changed result to a more meaningful coords array of objects.
// Create your markers without worrying about scope and without extensive For Loops
const markers = coords.map((coord) => {
return new google.maps.Marker({
position: new google.maps.LatLng(coord.lat, coord.lng),
map: map,
animation: google.maps.Animation.DROP
});
})
// Declare your bounds outside the map method (previous for loop)
const bounds = new google.maps.LatLngBounds();
// Iterate through markers and return coords for expanded viewport
markers.forEach((loc) =>{
loc = new google.maps.LatLng(loc.position.lat(), loc.position.lng());
return bounds.extend(loc);
});
map.fitBounds(bounds);
}
I am trying to use a 'foreach' loop to place a series of markers on the map using coordinates from a database. The retrieval of the data is not an issue so for now I'm not bothered about the map showing the correct locations. The issue is that when inside the 'foreach' loop, any code for the marker placement is immediately passed over. Any ideas?
Here is the current code:
<script>
function myMap() {
var lat = 52.4283381;
var lng = -1.601519;
var myLatLng = { lat: 52.428381, lng: -1.601519 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(lat, lng)
});
}
</script>
<script>
#foreach (var mapVars in ViewData.Model)
{
<text>
var marker = new google.maps.Marker
({
position: new google.maps.LatLng (52.428381 , -1.601519),
map: map,
title: "" + i,
});
</text>
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>
Try serialize your ViewData.Model to a javascript object and than loop from there.
Something like this:
<script>
function myMap() {
var lat = 52.4283381;
var lng = -1.601519;
var myLatLng = { lat: 52.428381, lng: -1.601519 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(lat, lng)
});
}
</script>
<script>
window.data = #(Html.Raw(js.Serialize(ViewData.Model)));
var markers = [];
for(i = 0; i < window.data.length; i++)
{
markers.push(new google.maps.Marker
({
position: new google.maps.LatLng (52.428381 , -1.601519),
map: map,
title: "" + i,
}));
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>
I am trying to add google maps to my web page, the web page has div with id of radar with width specified. I get coordinates from a second page using jquery ajax method, and plot them on the map using Marker. But only the last marker is displayed nothing else is displayed.
var global = new Array();
$(document).ready(function () {
console.log("ready!");
if ($("#StartingDate").val() != "") {
var start = $("#StartingDate").val();
var end = $("#EndingDate").val();
var id = $("#UserId").val();
$.ajax({
url: "GetData.aspx?StartingDate=" + start + "&EndingDate=" + end + "&UserId=" + id, async: false, success: function (result) {
var resp = result.split(",");
for (x = 0; x < resp.length - 1; x++) {
var cor = resp[x].split(";");
var lat = cor[0];
var lon = cor[1];
var date = cor[2]
var temp = [lat, lon, date];
global.push(temp);
}
}
});
}
});
$(document).ajaxComplete(function () {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("radar"), mapOptions);
for (var i = 0; i < global.length; i++) {
console.log(global[i]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(global[i][0]),parseFloat(global[i][1])),
title: global[i][2]
});
marker.setMap(map);
}
});
After the ajax call succeeds my variable named global is filled like this:
global = [
[
0: "33.622835",
1: "73.062932",
2: "16/06/2015 1:17:24 AM"
],....
];
Edit: Turns out you have to set the .ajaxComplete handler before you make the ajax request since you have set async to false.
Here is a working example.
I would suggest saving the markers in an array if you intend to use the markers later on(i.e.: move them, or remove them).
Only the last marker is displayed because you override it every time. What you need to do is save the marker in an array.
What i would do is create a function addMarker which creates a marker with the given coordinates and a title and returns it.
This would look something like this:
function addMarker(title, x, y, map){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x,y),
map: map,
title: title
});
return marker;
}
This function should be called where you currently are setting the marker in the for-loop:
for (var i = 0; i < global.length; i++) {
console.log(global[i]);
markerArray[i] = addMarker(global[i][2], global[i][0], global[i][1], map);
}
markerArray needs to be a global array like global.
I have a big problem with Google Maps Api and jQuery.
I need get markers from XML file, and show on map.
This is page with map:
http://szymonnosal.pl/sandbox/bsk/
And my code:
I initialize map:
var mapa; // obiekt globalny
var dymek; // okno z informacjami
var networks = [];
var locations = [];
function mapaStart()
{
var wspolrzedne = new google.maps.LatLng(50.0157021545812, 19.9094574787954);
var opcjeMapy = {
zoom: 15,
center: wspolrzedne,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
navigationControl: true,
mapTypeControl: true
};
mapa = new google.maps.Map(document.getElementById("mapka"), opcjeMapy);
dymek = new google.maps.InfoWindow();
loadNetworks();
google.maps.event.addListener(mapa,'click',function(){
resetLocations();
});
}
In loadNetwork() I load marker from XML file, I using jQuery:
function loadNetworks()
{
$.get('net.xml',function(xml){
$(xml).find("network").each(function(){
var lat = parseFloat($(this).find("lat").text());
var lon = parseFloat($(this).find("lon").text());
var icon_url = $(this).find("icon").text();
var SSID = $(this).find("SSID").text();
var BSSID = $(this).find("BSSID").text();
var AuthMode = $(this).find("AuthMode").text();
var Frequency = $(this).find("Frequency").text();
//alert(lat+' '+lon+' '+icon_url+' '+SSID+' '+BSSID+' '+AuthMode+' '+Frequency);
var marker = addNetwork(lat,lon,icon_url,SSID,BSSID,AuthMode,Frequency);
alert(marker.txt); // <- marker is correct object, because in alert pop-up is text from marker.
});
});
}
And in addNetwork I add marker on map.
function addNetwork(lat,lon,icon_url,SSID,BSSID,AuthMode,Frequency)
{
var size = new google.maps.Size(30,23);
var start_point = new google.maps.Point(0,0);
var start_hook = new google.maps.Point(15,12);
var icon = new google.maps.MarkerImage(icon_url, size, start_point, start_hook);
var marker = new google.maps.Marker(
{
position: new google.maps.LatLng(lat,lon),
title: BSSID,
icon: icon,
map: mapa
}
);
marker.txt = 'BSSID: '+BSSID+'<br/>SSID: '+SSID+'<br />AuthMode: '+AuthMode+'<br />Frequency: '+Frequency;
google.maps.event.addListener(marker,"click",function()
{
dymek.setPosition(marker.getPosition());
dymek.setContent(marker.txt);
dymek.open(mapa);
});
return marker;
}
If i use other function to load XML, it's correct:
function loadNetworks()
{
jx.load('getNetwork.php', function(xml)
{
var markery = xml.getElementsByTagName("network");
for(var i=0; i<markery.length; i++)
{
var lat = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var SSID = markery[i].attributes.getNamedItem("SSID").nodeValue;
var BSSID = markery[i].attributes.getNamedItem("BSSID").nodeValue;
var AuthMode = markery[i].attributes.getNamedItem("AuthMode").nodeValue;
var Frequency = markery[i].attributes.getNamedItem("Frequency").nodeValue;
var marker = addNetwork(lat,lon,ikona_url,SSID,BSSID,AuthMode,Frequency);
}
alert('Wczytano '+markery.length+' markerów z pliku networks.xml');
},'xml','get');
}
jx is function from: http://www.openjs.com/scripts/jx/
Do You have any idea, what is wrong in my code?
Looks to me like the icon_url is not defined. A test would be to change the marker definition to:
var marker = new google.maps.Marker(
{
position: new google.maps.LatLng(lat,lon),
title: BSSID,
// icon: icon,
map: mapa
});
This is on the live site:
var icon_url = jQuery(this).find("icon").text();
Not this (which is your posted code):
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
Your xml uses "ikona", and is the content of the element not an attribute.
<networks>
<network>
<lat>50.0158556853</lat>
<lon>19.9096229322</lon>
<SSID>untitled</SSID>
<BSSID>f0:7d:68:48:97:00</BSSID>
<AuthMode>[WPA-PSK-TKIP+CCMP][WPA2-PSK-TKIP+CCMP][ESS]</AuthMode>
<Frequency>2447</Frequency>
<ikona>http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png"</ikona>
</network>
</networks>
Is there a way you can convert XML to JSON as returned data?
If yes, then try vMap.
vMap is a lightning jQuery plugin with HTML 5 that makes Google Maps easy by sending a simple JSON Data Structure.
https://github.com/vhugogarcia/vMap
It helped me to solve a lot the markers problem with Google Maps, but also adds the feature for listing the locations if needed.
Feel free to modify it as your needs.
Hello
I'm looping over a JSON object and creating a new map marker for each item. After the marker is created, I push it to an array (var markers) for future manipulation. Problem is, when I try to access the array items (eg: console.log(markers[3])), I am given an "undefined" value.
Relevant code below:
var map;
var markers = [];
var activeFilters = [];
function initializeMap() {
var myLatlng = new google.maps.LatLng( 51.506873, -0.125141);
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById("location_map"), myOptions);
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
});
}
function addMarker(point, cat, weburl) {
var markerUrl = weburl;
var marker = new google.maps.Marker({
position: point,
map: map
});
marker.category = cat;
markers.push(marker);
};
initializeMap();
console.log(markers[3]);
Any help would be greatly appreciated.
get json runs asynchronously. try this:
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
console.log(markers);
});
Try to
console.log(markers[0]);
because looking at your code, there is just one element in markers array.
If you will put into that array 4 elements, then using markers[3] you will access fourth element.
try:
initializeMap();
setTimeout(function(){
console.log(markers[3]);
}, 10000);