I pass php $var into Javascript from controller. $var has fetched addresses from DB. And i put it in Javascript. Now i can see the addresses in the console. No problem with that, I don't know why syntax error pop up too.
This is how I insert it into JS.
function initMap(){
var options = {
zoom:8,
center:
'{!! $estates[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($estates as $addr)
'{!! $addr->address !!}',
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
my foreach running without a problem I can see the addreses in the console but also at this line: '{!! $estates[0]->address !!}' error pops up too. Actually I am seeing the address not this line.
error is this:
Uncaught SyntaxError: Invalid or unexpected token
Do you have any idea? am I making syntax mistake. But if do that then how can I retrieving the addresses at the console?
Also having this error too at the same line:
Undefined variable: estates (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php) (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php)
Controller
public function index()
{
$estates = DB::table("allestates")
->get();
return view("home", compact('estates'));
}
the topic is different the duplicated ones. it's not pure JS i am working with Laravel.
I think one of the addresses contains the ' character. To avoid it use the addslashes function. You could do that in the controller:
public function index()
{
$estates = DB::table("allestates")->get()->map(function($estate) {
$estate->address = addslashes($estate->address);
return $estate;
});
return view("home", compact('estates'));
}
And the according js would be:
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
Because you have multiple addresses, it means you will have multiple markers too. That being said your code should look something like:
function initMap(){
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
var map = new google.maps.Map(document.getElementById("map"), options);
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
var markers = [];
#foreach ($estates as $key => $estate)
markers[{{$key}}] = new google.maps.Marker({
position: new google.maps.LatLng({{$estate->lat}}, {{$estate->long}});
map: map
});
markers[{{$key}}].addListener('click', function () {
infoWindow.open(map, markers[{{$key}}]);
});
#endforeach
}
You can use php variables inside laravel blade files as
var options = {
zoom:8,
center:
'{{$estates[0]->address}}'
}
Related
I understand that this question asked MANY times, but I can't figure out how to make it work in my circumstances
It is a simple thing. I have url = WWW, but opening it in web browser you will see JSON.
I need to use JavaScript to get this JSON from URL and use it further.
<script>
var data;
$.getJSON("http://XXX?callback=?").done(function( data ) {
console.log('hello', data);
data = data;
initMap();
});
function initMap() {
//response from URL have to be used here
data.forEach((item) => {
});
}
</script>
DOes anyone know how to solve it? Ideally by using ASYNC
This is FULL CODE:
<script>
// data from server
$.getJSON("http://XXX?callback=?").then(function( data ) {
console.log('hello', data);
initMap(data);
});
// place you want to initially center the map on
const center = {
lat: 51.509865,
lng: -0.118092
}
function initMap(data) {
// set up map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: center.lat, lng: center.lng}
});
// loop over data from server
data.forEach((item) => {
// build a infowindow add dump the product table into it.
var infowindow = new google.maps.InfoWindow({
content: item.Products
});
// add and position the marker on the map
var marker = new google.maps.Marker({
position: {lat: item.Latitude, lng: item.Longitude},
map: map,
title: item.StoreName
});
// and event for opening the infowindow
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
JSON Looks like this :
[
{
"LatLan": "-3,22",
"Latitude": 22,
"Longitude": -3,
"StoreName": "XXX",
"Products": "XXX"
},
// carry on...
]
data = data
This will not work as you expect.
I would recommend passing the data into your initMap method: initMap(data)
function initMap(data) {
//response from URL have to be used here
data.forEach((item) => {
});
}
You would be better using a construct like this so you're not using a global variable, that's frowned upon. using a top level global variable like data you could stomp on any other modules that are using a global data variable (they shouldn't be, but...). Also, the line data = data is not going to assign to the global data variable, since the data variable that's in scope is the one inside the done block (I changed it to then()).
$.getJSON("http://XXX?callback=?").then(function( data ) {
console.log('hello', data);
initMap(data);
});
function initMap(data) {
//response from URL have to be used here
data.forEach((item) => {
});
}
Here is one way to loop through JSON:
var tableRow = '';
$.ajax({
url: 'https://randomuser.me/api/?&results=50&inc=name,email',
method: 'GET',
success: function(data) {
var items = '';
for (var i = 0; i < data.results.length; i++) {
items += '<tr><td>' + data.results[i].name.first + ' ' + data.results[i].name.last + '</td><td>' + data.results[i].email + '</td><td>' + data.results[i].email + '</td></tr>';
}
$("#dataTable tbody").html(items);
console.log(data);
},
error: function() {
var tableRow = '<tr><td>There is no data to display</td></tr>';
console.log(tableRow);
$("#dataTable tbody").html(tableRow);
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table" id="dataTable">
<thead>
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having an issue accessing a json file from a js script in a Laravel project.
I am using the Google maps API to add markers to a map, which are all currently hard-coded because I can only seem to access the json from within a listener function.
I am fully able to access my json through the placeMarker click listener, but when i try to make the "otherPlace" using json values, the values cannot be found. Not sure what's going on here.
Sorry for the likely noob question but I am stumped and couldn't find any similar questions.
Map script Example:
function myMap() {
var mapProp= {
center:new google.maps.LatLng(44.5458062,-83.54936229999996),
zoom:8,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var place = new google.maps.LatLng(44.453,-83.45773609999998);
var placeMarker = new google.maps.Marker({position: place});
var otherPlace = new google.maps.LatLng(json.locations[4].lat,json.locations[4].lng);
var otherPlaceMarker = new google.maps.Marker({position: otherPlace});
placeMarker.setMap(map);
otherPlaceMarker.setMap(map);
placeMarker.addListener('click', function() {
map.setZoom(13);
map.setCenter(placeMarker.getPosition());
console.log(json.locations[5].address);
var infowindow = new google.maps.InfoWindow({
//content: json.locations[5].name + "\r\nAddress: " + json.locations[5].address
});
infowindow.setContent(
"<p>" + json.locations[5].name + "<br />" + json.locations[5].address + "<br/> <a href='#'>Get Directions</a> </p>"
);
infowindow.open(map,placeMarker);
});
}
In my controller I grab the json file and pass it to the view
public function locations() {
$path = storage_path() . "/json/locations.json";
$json = json_decode(file_get_contents($path), true);
return view('home/locations', compact('json'));
}
In my locations.blade.php I add the map script and pass the json to javascript
#section('scripts')
<script src="/js/locationsMap.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{ env('APP_GOOGLE_MAPS') }}&callback=myMap"></script>
<script>
var json = {!! json_encode($json) !!};
</script>
#endsection
Try removing var from var json if that doesn't work, put your function below json = {!! json_encode($json) !!}; and try then
I'm working with Googlemaps now. I use lattitude and longitude stored in the database. To call the data, I use simple ajax and it shows the latt and long as I wish.
However, It takes a long time to show the map based on the latt and long. Otherwise, It does not show anything. I don't know. How can I handle this?
Updated:
It looks there's a problem with the event.key onkeypress. I tried
clean code for that and it doesn't show anything !. ex: jsfiddle But That keyboard works on other code.
Here's the complete code:
JS/Ajax call the database through file inc.php:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function strQuery(str) {
if (str.length == 0) {
document.getElementById("valdata").value = "-33.8474, 151.2631";
return;
}
else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("valdata").value = xmlhttp.responseText;
script_dkill()
}
}
xmlhttp.open("POST", "inc.php?q="+str, true);
xmlhttp.send(null);
}
}
//start: calling maps
var map;
var strlng;
function script_dkill() {
strlng = document.querySelector("#valdata").value;
if (strlng) {
var latlng = new google.maps.LatLng(strlng);
var myOptions = {
zoom: 12,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker(new google.maps.LatLng(strlng), map);
}
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
return marker;
}
</script>
Here's the target(Output) in HTML:
<input id="qfront" name="qfront" placeholder="Ketik Nama Kampus ..." value="" type="text" onKeyPress="strQuery(this.value)"/>
<input id="valdata" name="valdata" type="text"/>
<div id="map_canvas" style="width:99.8%; height:280px; margin:0px; padding:0px;"></div>
and, here's the PDO the way I grab the data of latt and long (inc.php):
<?php
include('deep/cf/dbbs.php');
error_reporting(E_ALL);
?>
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
$result = $uQuery->fetch(PDO::FETCH_ASSOC);
if ($result>0){
$googlemap=$result['googlemap'];
echo $googlemap;
}
else{
echo "<script>alert('Rent-house not registered yet');</script>";
}
?>
It's impossible to give you how the code running here. if you don't mind, please check here:
TEST-REAL-PAGE
Use keyword: "Universitas Lampung" since it's already inside the db.
I tends to focus on how the events work which I found it was wrong.
Data from db is interpreted as one value, ex: -2.9549663, 104.6929232
I must convert it into array first before called by JS in googlemap.
So, what makes it gray? It is because it didn't find the correct data format (like: -2.9549663, 104.6929232) in array. That's stupid of me.
Here's the way I convert which makes me stupid in a week:
var strlng = document.querySelector("#valdata").value;
var test1 = strlng.split(',');
var x = test1 [0];
var y = test1 [1];
After that, insert the x and y into the value of latt and long (latt and long is in array value), as follow:
var map;
function script_dkill() {
var strlng = document.querySelector("#valdata").value;
var test1 = strlng.split(',');
var x = test1 [0];
var y = test1 [1];
var latlng = new google.maps.LatLng(x,y);
var myOptions = {
zoom: 12,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker(new google.maps.LatLng(x,y), map);
}
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
return marker;
everything finally goes so amazing! Done.
now I learn one more from JS.
Hi everyone i develop web map using openlayer.
i use geojson, i have this code from :
https://scraperwiki.com/views/openlayers_geojson_example/edit/
this is code :
<script type="text/javascript">
// Start position for the map (hardcoded here for simplicity)
var lat=50.90685
var lon=-1.4029
var zoom=12
var map; //complex object of type OpenLayers.Map
//Initialise the 'map' object
$(function() {
$.getJSON("http://mapit.mysociety.org/area/66016.geojson",
"callback=?",
function(data, textStatus, jqXHR) {
map = new OpenLayers.Map('map', {
layers: [
new OpenLayers.Layer.OSM.Mapnik("Mapnik"),
],
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution()],
maxResolution: 'auto',
});
var lonLat = new OpenLayers.LonLat(lon, lat)
.transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
map.setCenter(lonLat, zoom);
var vector_layer = new OpenLayers.Layer.Vector("GeoJSON");
var geojson_format = new OpenLayers.Format.GeoJSON();
var geometry = geojson_format.parseGeometry(data);
geometry.transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
var feature = new OpenLayers.Feature.Vector(geometry);
vector_layer.addFeatures([feature]);
map.addLayer(vector_layer);
})
});
</script>
in :
$.getJSON("http://mapit.mysociety.org/area/66016.geojson",
"callback=?",
it works when i call from iis localhost
i try to change like this :
$.getJSON("assets/json/66016.geojson",
"callback=?",
but it didnt work, :(
please help me why and how to make this work.
this is the wrong :
HTTP Error 404.0 - Not Found
localhost --- >/assets/json/66016.geojson?callback=jQuery152048599341535009444_1366340277133&_=1366340277237
Try this
$.getJSON("/assets/json/66016.geojson",
"callback=?",
Sorry guys, finnaly i get my answer this is the solve :
$.getJSON("assets/json/66016.geojson",
"callback=?",
just erase "callback=?",
$.getJSON("/assets/json/66016.geojson",
I am trying to add markers to my Google map dynamically using a combination of ajax and php.
The first part of the code sends the latlng to the php file. The php file then returns the marker location needed.
When I alert the return part (ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY), it looks OK, but I cant seem to add the markers from the return on to my map.
See code below.
//SEND DATA TO URL (send to php file)
//RETURN DATA FOR PLACE MARKERS (this is what the return php file produces)
Many thanks,
//SEND DATA TO URL
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}}
xmlHttp.open("POST",'MYPHPFILE',true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("LATLON="+strLAT);
//RETURN DATA FOR PLACE MARKERS
var wxlatlng = new google.maps.LatLng(52,1);
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: '../../icons/flags/traffic_light_red.png',
title: 'TEST', });
//RETURN DATA FOR PLACE MARKERS
var wxlatlng = new google.maps.LatLng(52,1.1);
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: '../../icons/flags/traffic_light_red.png',
title: 'TEST', });
//ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
alert($('#ResponseDiv').text());
}
The answer i found for my question was to use the php file to create the markers xml file and load the xml file via jQuery response
See code below;
jQuery.get(YOURXMLFILE, function(data) {
jQuery(data).find("marker").each(function() {
var eachMarker = jQuery(this);
var markerCoords = new google.maps.LatLng(
parseFloat(eachMarker.find("Lat").text()),
parseFloat(eachMarker.find("Lng").text())
);
var header = eachMarker.find("title").text();
var content = eachMarker.find("Content").text();
var wxicon = eachMarker.find("icon").text();
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
});
});
});