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 know the problem but can’t find the solution.
I want to get all markers in my location array.
Here is my code:
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var locations = new Array();
var lati = "";
var longi = "";
var cityfrom = "";
posts.forEach((item, index) => {
lati = item.acf.maps.lat;
longi = item.acf.maps.lng;
cityfrom = item.title.rendered;
});
locations = [
{
lat: lati,
lng: longi,
city: cityfrom
},
];
CodePen
You only assign the last values of lati, longi, and cityfrom to a single item in the array, and easier option would be to use Array.map() to create the array:
map = new google.maps.Map(document.getElementById('map'), mapOptions);
const locations = posts.map((item, index) => ({
lati: item.acf.maps.lat,
longi: item.acf.maps.lng,
cityfrom: item.title.rendered,
}));
I am trying to update map data through ajax but ist's not working here is my code:
$(document).ready(function() {
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/users/online-peoples'; ?>",
type:"POST",
})
.done(function(result){
var icon1 = 'https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0';
if(result){
var map;
function initMap() {
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng('30.7333','76.7794'),
mapTypeControlOptions: {
mapTypeIds: ['roadmap']
}
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var online =result;
var mapIcons = ['https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0'];
var person = {3:"Customer1 : ", 4:"Driver1 : "};
var arr = [];
var marker, i;
for (i = 0; i < online.length; i++)
{
console.log(online[i]);
arr.push(new google.maps.LatLng(online[i][0], online[i][0]));
marker = new google.maps.Marker({
position: new google.maps.LatLng(online[i][0], online[i][1]),
icon:mapIcons[0],
suppressMarkers: true,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(person[online[i][4]]+online[i][2]+', Phone : '+online[i][5]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
}
});
}
setInterval(makeRequest, (10 * 1000));
});
The above code update map icons and date every 10 secondas but it's not working.Where i am doing wrong ?
This is my data :
[
["30.740395","76.7804482","Dbd Dbdhdh","1",4],
["30.740395","76.7804482","Sam Sam","1",4],
["30.7404344","76.7804032","Sumit Kumar","1",4],
["30.74041018","76.78060575","Chetan Nagrath","3",4],
["30.7403555","76.7804933","Sahil Kapoor","2",4],
["30.7403648","76.7805835","paras kumar",1,3]
]
You are not initializing your map. Since its inside initMap map function no one is calling it.
And there is no need to initialize every time when you got the data from the server. Just initialize once and use the same map object for your other works also.
And be careful while getting the data, You are trying to get the data in the index 5. But the array has only 0 to 4.
Try in the below fashion.
$(document).ready(function() {
function makeRequest() {
$.ajax({
url : "url",
type : "POST",
}).done(function(result) {
if (result) {
console.log("You Got your data", result);
}
});
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 12,
center : new google.maps.LatLng('30.7333', '76.7794'),
mapTypeControlOptions : {
mapTypeIds : [ 'roadmap' ]
}
});
setInterval(makeRequest, (10 * 1000));
});
Here you will get data after 10 second. If you want at the first time itself means call makeRequest after initialization of map once.
I will start by saying that I am relatively new to JS, so please forgive my ignorance if this is obvious.
I am trying to add markers to a google map. I have created an array coordList, then used the geocoding api to get the lag and long from the addresses and pushed them into coordList.
I am now trying to use the coordList array to plot markers on the map, however I cannot seem to get the values from the coordList array. When I run console.log(typeof coordList) - it tells me it's an object, but when i look at the array with console.log(coordList) it just looks like a normal array?
var coordList = [];
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLong(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
var coords = [];
coords.push(lat);
coords.push(lng);
//push coords into coordList
coordList.push(coords);
});
}
}
// Loop through the results array and place a marker for each
// set of coordinates.
function addMarkers(coordList) {
for (var i = 0; i < coordList.length; i++) {
var coords = coordList[i];
var latLng = new google.maps.LatLng(coords[0],coords[1]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
getLatLong(address);
addMarkers(coordList);
Your problem is that $.getJSON() is an asynchronous request and your code executes addMarkers() before than $.getJSON() finishes, so coordList is empty.
You can add the markers inside $.getJSON() callback. For example:
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLongAndAddMarkers(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var latLong = new google.maps.LatLng(data.results[0].geometry.location);
//add markers here
var marker = new google.maps.Marker({
position: latLong,
map: map
});
});
}
}
getLatLongAndAddMarkers(address);
I am trying to render Google map with Latitude and Longitude from my MVC Model by using different examples. Google Map is displaying fine but it is not displaying the markers. I am very new to the Google Maps and feeling completely clueless about it. Can please anyone tell me how I can get the markers?
My MVC view is as follow
if (Model.WidgetType == "Map")
{
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$.get("/Home/GetMapLocations", function(data){
$.each(data, function(i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});
});
#*var data = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.lstMapLocations));
$.each(data, function (i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});*#
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
}
MVC Controller is as follow
public ActionResult GetMapLocations()
{
var lstMapLocations = new List<MapLocation>();
var mapLocationModel1 = new MapLocation
{
EngineerName = "Engineer1",
SiteName = "Site1",
Latitude = 51.507351,
Longitude = -0.127758,
LstDouble = new List<double>()
};
var mapLocationModel2 = new MapLocation
{
EngineerName = "Engineer2",
SiteName = "Site2",
Latitude = 51.481728,
Longitude = -0.613576,
LstDouble = new List<double>()
};
var mapLocationModel3 = new MapLocation
{
EngineerName = "Engineer3",
SiteName = "Site3",
Latitude = 51.628611,
Longitude = -0.748229,
LstDouble = new List<double>()
};
var mapLocationModel4 = new MapLocation
{
EngineerName = "Engineer4",
SiteName = "Site4",
Latitude = 51.26654,
Longitude = -1.092396,
LstDouble = new List<double>()
};
lstMapLocations.Add(mapLocationModel1);
lstMapLocations.Add(mapLocationModel2);
lstMapLocations.Add(mapLocationModel3);
lstMapLocations.Add(mapLocationModel4);
foreach(var item in lstMapLocations)
{
item.LstDouble.Add(item.Latitude);
item.LstDouble.Add(item.Longitude);
item.LatLong = item.LstDouble.ToArray();
}
return Json(lstMapLocations);
}
I have found a work around to my problem and thought to share it for those who may stumble upon a similar issue. Courtesy stack overflow post particularly the answer posted by Atish Dipongkor. There may well be a better alternative to this problem but this approach has resolve my problem. I have made little change in that answer as Atish has used apostrophes while retrieving data from model which can break the functionality if any of the model field has string data with apostrophe in it. My appended solution with the above dummy data (in my question) is as follow
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 8,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
#foreach (var item in Model.lstMapLocations)
{
<text>
var markerLatLong = new google.maps.LatLng(#(item.Latitude), #(item.Longitude));
var markerTitle = #Html.Raw(Json.Encode(item.EngineerName));
var markerContentString = #Html.Raw(Json.Encode(item.EngineerName)) + " At " + #Html.Raw(Json.Encode(item.SiteName));
var infowindow = new google.maps.InfoWindow({
content: markerContentString
});
var marker = new google.maps.Marker({
position: markerLatLong,
title: markerTitle,
map: map,
content: markerContentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
I have JSON data:
"geometry":{"type":"Point","coordinates":[95.9174,3.8394,59]},"id":"us10002b0v"
I need to extract each value in coordinates which is comma separated. In PHP I would do extract(",",$geometry[coordinates]);. Is there any possible in JavaScript to do so?
Source Json from here : http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week
This is my code :
google.maps.event.addDomListener(window, 'load', function() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: { lat: 7.8, lng: 98.3},
zoom: 4,
styles: mapStyle
});
map.data.setStyle(styleFeature);
infowindow = new google.maps.InfoWindow({
content: '<div class = "corp" style="width: 260px; height: 200px">' + '</div>'
})
//InfoWindow
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map,'click',function() {
infowindow.close();
});
map.data.addListener('click', function(event) {
var place = event.feature.getProperty('place');
var mag = event.feature.getProperty('mag');
var depth = event.feature.getProperty('geometry');//I need the depth from this line which is arrayed
var link = event.feature.getProperty('url');
var jsonTime = event.feature.getProperty('time');
var humanTime = new Date('jsonTime');
infowindow.setContent('<div><h3>'+place+'</h3><p>Mag: '+mag+'<br />Depth '+depth+'<br />Time : '+humanTime+'<br />More</p></div>');
infowindow.setPosition(event.feature.getGeometry().get());
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-30)});
infowindow.open(map);
});
Yes, you can get them as array values:
var my_json = '{"geometry":{"type":"Point","coordinates":[95.9174,3.8394,59]},"id":"us10002b0v"}';
var my_obj = JSON.parse(my_json);
var lat = my_obj.geometry.coordinates[0];
var lng = my_obj.geometry.coordinates[1];
console.log( lat ); //95.9174
console.log( lng ); //3.8394
You could use
var myObject = JSON.parse("<your-json-string>");
This will parse your JSON into a JavaScript object which you can traverse in the usual way.