Dynamically adding markers to Google maps - javascript

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,
});
});
});

Related

Php $var in Javascript function Laravel

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}}'
}

I am getting error 419 in laravel while displaying something on map eventhough my path is correct

Im creating an application using google maps api that allows the user to add a marker at a specific location
but when im clicking on the map to add the location, all data i get back is correct but i get the response code of error 19...this is my code for saving the data
function saveData(lat,lng)
{
console.log("LAT:"+lat+" LNG:"+lng);
var description = document.getElementById('manual_description').value;
var formData = new FormData();
console.log("DESC:"+description);
formData.append("latitude", lat); //outputs correctly
formData.append("longitude", lng);//outputs correctly
formData.append("description", description); //outputs correctly
console.log(formData.get("latitude")+" "+formData.get("longitude")+" "+formData.get("description"));
downloadUrl(formData, function(data, responseCode) {
console.log("RESP:"+responseCode);
console.log(data.length);
if (responseCode === 200 && data.length > 1) {
var markerId = getMarkerUniqueId(lat,lng); // get marker id by using clicked point's coordinate
var manual_marker = markers[markerId]; // find marker
manual_marker.setIcon(purple_icon);
infowindow.close();
infowindow.setContent("<div style=' color: purple; font-size: 25px;'> Waiting for admin confirm!!</div>");
infowindow.open(map, manual_marker);
}else{
console.log("RESPONSECODE: "+ responseCode); //419
console.log("DATA: "+data); //html data with title of Page Expired
infowindow.setContent("<div style='color: red; font-size: 25px;'>Inserting Errors</div>");
}
});
function downloadUrl(formData, callback)
{
var xhttp = new XMLHttpRequest;
xhttp.onreadystatechange = function() {
console.log(xhttp.readyState);
if (xhttp.readyState == 4) {
callback(xhttp.responseText, xhttp.status);
}
};
xhttp.open("POST", "http://localhost/cacheFinder/public/save");
xhttp.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
xhttp.send(formData);
}
this is my route Route::post('save', 'MarkersController#save');
and this is the save function :
public function save(Request $request){
$lat = $request->input("latitude");
$lng = $request->input("longitude");
$description = $request->input("description");
Marker::create([
'latitude'=>$lat,
'longitude'=>$lng,
'description'=>$description
]);
return redirect('usermap');
}
Any help would be much appreciated
add this to your VerifyCsrfToken middleware
protected $except = [
'/cacheFinder/public/*'
];
or
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader('X-CSRF-TOKEN',window.Cookies.get('_csrf'));
this is because of https://laravel.com/docs/5.7/csrf disable route protection in CsrfMiddleware or post valid value

Google map and places api exceeded your request quota for this API

i have create website on 000webhost. i use map on it and create new google api key but issue is that when i hit the api for first time through message exceeded your 'request quota for this API' how ever i never hit it before i hit the api for the first time with new api key. this is my php script.i need help
function initMap() {
var map = new google.maps.Map(document.getElementById('show_map'), {
center: {lat: 33.6518, lng: 73.1566},
zoom: 13
});
var input = document.getElementById('shopadd');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'pk'}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
// Set the data fields to return when the user selects a place.
autocomplete.setFields(['address_components', 'geometry', 'name']);
autocomplete.setOptions({strictBounds: true});
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
var location = "Address " + place.formatted_address;
location += "Latitude " + place.geometry.location.lat();
location += "Longitude " + place.geometry.location.lng();
var lat = place.geometry.location.lat();
document.getElementById('lat').value = lat;
var lng = place.geometry.location.lng();
document.getElementById('lng').value = lng;
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var add = '';
if (place.address_components.length>0) {
add = add.concat(
(place.address_components[0] && place.address_components[0].short_name || ''),' ',
(place.address_components[1] && place.address_components[1].short_name || ''),' ',
(place.address_components[2] && place.address_components[2].short_name || ''),' ');
}
document.getElementById('add').value = add;
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = add;
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key="my key"&libraries=places&callback=initMap" async defer></script>
Google changed their pricing model. The new plan gives you more flexibility and control over how you use our APIs. You can use as much or as little as you need and only pay for what you use each month.
As of July 16, 2018:
The Google Maps Platform APIs are billed by SKU.
Usage is tracked for each Product SKU, and an API may have more than one Product SKU.
Cost is calculated by: SKU Usage x Price per each use.
For each billing account, for qualifying Google Maps Platform SKUs, a $200 USD Google Maps Platform credit is available each month, and automatically applied to the qualifying SKUs.
For more information, visit this Link

JSON passed through Laravel view only accessible through listener function in 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

maps only show gray with certain latt and long grabbed from database

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.

Categories