I am new to Openlayers3.....I am trying to load data from database using ajax & php to load vector data to openlayers3,I am stuck and don't know what is the problem.
here is my code
Can anyone help me in that?
$(document).ready(function()
{
//extent of the map
view = new ol.View({
center:ol.proj.transform([125.7799,8.7965], 'EPSG:4326', 'EPSG:3857'),
zoom:11,
maxZoom:18,
minZoom:2
});
//BaseLayer
var baseLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// create a vector source that loads a GeoJSON file
var vectorSource = new ol.source.Vector({
projection: 'EPSG:4326',
url: 'data/Boundaries.geojson',
format: new ol.format.GeoJSON()
});
var geoJSONFormat = new ol.format.GeoJSON();
var farmersSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = 'allfarmers_geojson.php?p=' + extent.join(',');
$.ajax({
url: url,
success: function(data) {
var features = geoJSONFormat.readFeatures(data);
farmersSource.addFeatures(features);
}
});
},
strategy: ol.loadingstrategy.bbox
});
// Polygons
var createPolygonStyleFunction = function() {
return function(feature, resolution) {
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 1
}),
fill: new ol.style.Fill({
color: '#faeaac'
}),
//text: createTextStyle(feature)
});
return [style];
};
};
// a vector layer to render the source
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style:createPolygonStyleFunction()
});
var farmersLayer = new ol.layer.Vector({
source: farmersSource
//style:createPolygonStyleFunction()
});
//Map
var map = new ol.Map({
target:'map',
controls:ol.control.defaults().extend([
new ol.control.ScaleLine(),
new ol.control.ZoomSlider()
]),
renderer: 'canvas',
layers:[baseLayer,vectorLayer,farmersLayer],
view:view
});
//////////styling features and with mouse over color change/////////////
var highlightStyleCache = {};
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector(),
map: map,
style: function(feature, resolution) {
var text = resolution < 5000 ? feature.get('NAME_3') : '';
if (!highlightStyleCache[text]) {
highlightStyleCache[text] = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#f00',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.1)'
}),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
text: text,
fill: new ol.style.Fill({
color: '#f00'
})
})
});
}
return highlightStyleCache[text];
}
});
var highlight;
var displayFeatureInfo = function(pixel) {
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
if (feature !== highlight) {
if (highlight) {
featureOverlay.getSource().removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
};
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
map.on('click', function(evt) {
displayFeatureInfo(evt.pixel);
});
//////////End of styling features and with mouse over color change/////////////
});
and here is my php file
<?php
$conn = new PDO('mysql:host=localhost;dbname=FarmersDB','root','admin');
$sql = 'SELECT *, _coordinates__latitude AS x, _coordinates__longitude AS y FROM farmers';
if (isset($_GET['bbox']) || isset($_POST['bbox'])) {
$bbox = explode(',', $_GET['bbox']);
$sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y <= ' . $bbox[3] . ' AND y >= ' . $bbox[1];
}
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
unset($properties['x']);
unset($properties['y']);
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['x'],
$row['y']
)
),
'properties' => $properties
);
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
No exactly sure what problem you're having but try this..You probably need to set the right projection and parse the data response from the server..Projection is EPSG:3857 by default:
success: function(data) {
var JSONData;
try {
JSONData = JSON.parse(data);
} catch(err) {
alert(err);
return;
}
var format = new ol.format.GeoJSON();
var features = format.readFeatures(JSONData, {
featureProjection: 'EPSG:3857'
});
farmersSource.addFeatures(features);
farmersSource.changed();
}
});
Also, on var vectorSource change the project to EPSG:3857. Another thing, you need to add the vectorloader property to you source.vector. For example:
var locationSource = new ol.source.Vector({
url: loc_url,
format: new ol.format.GeoJSON({
defaultDataProjection :'EPSG:3857'
}),
loader: vectorLoader,
strategy: ol.loadingstrategy.all
});
The vectorLoader function looks like this and makes your ajax calls to the server. Special note on loader functions - When clear() is called on the source layer, it will trigger the vector loader function again:
var vectorLoader = function(extent, resolution, projection) {
var url = this.getUrl();
utils.refreshGeoJson(this);
}
var utils = {
refreshGeoJson: function(source,url) {
var now = Date.now();
if (typeof url == 'undefined') {
url = source.getUrl();
}
url += '?t=' + now; //Prevents browser caching if retrieving a geoJSON file
console.info('refreshGeoJson url: ' + url);
this.getJson(url).when({
ready: function(response) {
var JSONResponse;
try {
JSONResponse = JSON.parse(response);
} catch(err) {
alert(err + ' - ' + url);
return;
}
var format = new ol.format.GeoJSON();
var features = format.readFeatures(JSONResponse, {
featureProjection: 'EPSG:3857'
});
source.addFeatures(features);
source.changed();
}
});
},
getJson: function(url) {
var xhr = new XMLHttpRequest(),
when = {},
onload = function() {
console.log(url + ' xhr.status: ' + xhr.status);
if (xhr.status === 200) {
console.log('getJson() xhr: ');
console.dir(xhr);
console.log('getJson() xhr.response: ');
console.dir(xhr.response);
when.ready.call(undefined, xhr.response);
}
if (xhr.status === 404) {
console.log('map file not found! url: ' + url);
}
},
onerror = function() {
console.info('Cannot XHR ' + JSON.stringify(url));
};
xhr.open('GET', url, true);
xhr.setRequestHeader('cache-control', 'no-store');
xhr.onload = onload;
xhr.onerror = onerror;
xhr.send(null);
return {
when: function(obj) { when.ready = obj.ready; }
};
}
};
Threw in a lot of extras here because I'm not sure what your problem is with your code. The example above work great for me retrieving geoJSON files from the server that are periodically changed..It should work the same for you if calling a PHP script, just make sure that the script returns geoJSON data according to this spec: http://geojson.org/geojson-spec.html
Related
In my Laravel Application i use google map to Display Route and Distance Between Two Places. after setting google map, i test my app. its display as Blank Screen. I even registered the application using a key that I applied for on Google's website. I have been working on this for 2 hours and cannot figure it out.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY API KEY&libraries=places&callback=initMap&sensor=false" async defer></script>
<script type="text/javascript">
function GetRoute() {
source = document.getElementById("pickupaddress").value;
destination = document.getElementById("deliveryaddress").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var dvDistance = document.getElementById("distanceops");
dvDistance.innerHTML = "";
dvDistance.innerHTML += distance;
} else {
alert("Unable to find the distance via road.");
}
});
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 4.2105, lng: 101.9758},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('pickupaddress');
var destinationInput = document.getElementById('deliveryaddress');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var deliveryrestrictOptions = {componentRestrictions: {country: 'my'},placeIdOnly: true};
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, deliveryrestrictOptions);
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput,deliveryrestrictOptions);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
GetRoute();
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
window.ParsleyConfig = {
errorsWrapper: '<div></div>',
errorTemplate: '<span class="error-text"></span>',
classHandler: function (el) {
return el.$element.closest('input');
},
successClass: 'valid',
errorClass: 'invalid'
};
</script>
I have worked on google maps. Google maps won't load inside a modal or any hidden divs (for perf reasons).
Here is what you do. Trigger resize on the map and it should render the map.
google.maps.event.trigger(map, 'resize') where map is your map instance name.
currently i am create a small that display markers on google map. Coordinates come from mysql database but i getting the error i don't know why it's came.
ERRor - XMLHttpRequest cannot load http://localhost:8080/markers.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.7:8100' is therefore not allowed access. The response had HTTP status code 404.
markers.php
<?php
//Create a connection to the database
$mysqli = new mysqli("localhost", "test");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
//The default result to be output to the browser
$result = "{'success':false}";
//Select everything from the table containing the marker informaton
$query = "SELECT * FROM marker";
//Run the query
$dbresult = $mysqli->query($query);
//Build an array of markers from the result set
$markers = array();
while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){
$markers[] = array(
'id' => $row['id'],
'name' => $row['name'],
'lat' => $row['lat'],
'lng' => $row['lng']
);
}
//If the query was executed successfully, create a JSON string containing the marker information
if($dbresult){
$result = "{'success':true, 'markers':" . json_encode($markers) . "}";
}
else
{
$result = "{'success':false}";
}
//Set these headers to avoid any issues with cross origin resource sharing issues
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
//Output the result to the browser so that our Ionic application can see the data
echo($result);
?>
app.js
angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
})
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function($http) {
var markers = [];
return {
getMarkers: function(){
return $http.get("http://localhost:8080/markers.php").then(function(response){
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function($cordovaGeolocation, Markers){
var apiKey = false;
var map = null;
function initMap(){
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function(){
//Load the markers
loadMarkers();
});
}, function(error){
console.log("Could not get location");
//Load the markers
loadMarkers();
});
}
function loadMarkers(){
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function(markers){
console.log("Markers: ", markers);
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var markerPos = new google.maps.LatLng(record.lat, record.lng);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
});
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function(){
initMap();
}
}
})
.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {
});
There is a configuration to do with Ionic :
http://ionicframework.com/docs/cli/test.html
Or if you are using google chrome you can add this plugin, it solve the problem for me :
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
Hope it should help you
I must adjust a website, but I don't understand this function:
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow;
var appena_entrato = true;
var mappa_attiva = "tt";
-- Initialize_map
function initialize_map() {
markersArray = [];
var myLatlng = new google.maps.LatLng(45.6841895,11.4775636);
var myOptions = {
zoom: 14,
maxZoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: false,
streetViewControl: false
}
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas-"+mappa_attiva), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(45.6841895,11.4775636),
map: map,
title:"COMPANY NAME"
});
marker.setMap(map);
var contentString = '<div>'+
'<h2>COMPANY NAME</h2>'+
'<div style="width:400px;">'+
'<p>ADDRESS<br>' +
'Ph. +39 0000- Fax. +39 00000</p>'+
'</div>'+
'</div>';
marker.infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
marker.infowindow.open(map,marker);
});
markersArray.push(marker);
for (i in markersArray) {
markersArray[i].infowindow.open(map,markersArray[i]);
}
getLocation();
}
-- GetLocation
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
//console.log("Geolocation not supported!");
}
}
-- ShowPosition
function showPosition(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatlng);
map.setZoom(9);
coordsAddress(position.coords.latitude,position.coords.longitude,function(results){
for (var i=0; i<results.length; i++) {
for (var b=0; b<results[i].types.length; b++) {
if (results[i].types[b] == "administrative_area_level_2") {
var indice = i;
}
}
}
for (var i=0; i<results[indice].address_components.length; i++) {
for (var b=0; b<results[indice].address_components[i].types.length; b++) {
if (results[indice].address_components[i].types[b] == "administrative_area_level_2") {
var postalCode = results[indice].address_components[i].short_name;
}
}
}
$("#provincia option:selected").removeAttr("selected");
$("#provincia option[value="+postalCode+"]").prop("selected",true);
mostra_coords(position.coords.latitude, position.coords.longitude, 50);
});
}
-- Code Address
function codeAddress(zipCode,country,callback) {
geocoder.geocode({address: zipCode, region: country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
-- CoordsAddress
function coordsAddress(latitude,longitude,callback) {
var myLatlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({'latLng': myLatlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
--Add marker
function add_spillo(indirizzo) {
var id = indirizzo.attr("id");
var geo = indirizzo.attr("rel");
var text = indirizzo.parent().html();
var icona = 'img/point.png';
indirizzo = geo.split(",");
var myLatlng = new google.maps.LatLng(indirizzo[0],indirizzo[1]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: icona
});
marker.infowindow = new google.maps.InfoWindow({
content: text
});
google.maps.event.addListener(marker, 'click', function () {
marker.infowindow.open(map, marker);
});
markersArray.push(marker);
bounds.extend(myLatlng);
}
-- Map centre
function centra_mappa(coords) {
var lat = coords.lat();
var lon = coords.lng();
var max_lon = map.getBounds().getNorthEast().lng();
var max_lat = map.getBounds().getNorthEast().lat();
var min_lon = map.getBounds().getSouthWest().lng();
var min_lat = map.getBounds().getSouthWest().lat();
max_lon = Math.max(lon, max_lon);
min_lon = Math.min(lon, min_lon);
max_lat = Math.max(lat, max_lat);
min_lat = Math.min(lat, min_lat);
var ne = new google.maps.LatLng(max_lat, max_lon);
var sw = new google.maps.LatLng(min_lat, min_lon);
var nuovi_bordi = new google.maps.LatLngBounds(sw, ne);
map.fitBounds(nuovi_bordi);
}
-- Delete Overlays
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].infowindow.close();
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
-- Coords Show
function mostra_coords(lat, lng, distance) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
lat: lat,
lng: lng,
distance: distance,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search1");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
appena_entrato = false;
});
}
-- Provincia Show
function mostra(provincia) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
provincia: provincia,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search2");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
--Nazione Show
function mostra_nazione(nazione) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
country: nazione,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search3");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize_map);
$(document).ready(function(){
$("#provincia-ttt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#provincia-tt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#nazione-ttt").change(function(){
console.log($(this).val());
if ($(this).val() == "IT") $("#teen_provincia").show();
else {
$("#teen_provincia").hide();
mostra_nazione($(this).val());
}
});
$('#tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
if ($(this).attr('href') == "#orange") {
mappa_attiva = "ttt";
} else {
mappa_attiva = "tt";
}
initialize_map();
$("#provincia-"+mappa_attiva).val("");
$("#boxNegozi-"+mappa_attiva+" ul").html("");
});
});
-- I MADE THIS PHP PAGE BUT DON'T WORK, WHERE I MAKE ERROR? thanks in advance
<?
$dbname ='ltaketwd_db'; //Name of the database
$dbuser ='ltaketwd_admin'; //Username for the db
$dbpass ='Twork.01'; //Password for the db
$dbserver ='localhost'; //Name of the mysql server
$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$query = mysql_query("SELECT * FROM negozi");
while ($row = mysql_fetch_array($query)){
$lat=$row['lat'];
$lng=$row['lng'];
$distance=$row['distance'];
$name=$row['name'];
$indirizzo=$row['indirizzo'];
$provincia=$row['provincia'];
$nazione=$row['nazione'];
}
?>
AJAX = Asynchronous JavaScript and XML.
In short; AJAX allows you to load data in the background, manipulate it and display it on the webpage, without needing a page reload.
Have a look at jQuery's documentation for load().
You'll see that load() takes up to three parameters, which is what happens here :
$("#boxStore-"+active_map+" ul") // the element you want as container for your document
.load(
customurl, // 1) the page/document you want to load in the container
{lat:lat, ..... }, // 2) variables you pass to the page so it generates differently
function(data) {
/* 3) callback function, that will be executed after load() is finished. "data" is the page/document you called. */
}
);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am trying to make an app where users can crop the image then save then can download it, but after cropping when i click on save button the png image created is of 0kb...
what could be the error?
this is my js file
function getIndex(e) {
var t = c.getObjects();
for (var n in t) {
if (t[n] == e) {
return n
}
}
}
function loadingShow(e) {
$("#overlay_loading").show();
$("#overlay_loading #load_message").html(e);
$("body").css("overflow", "hidden")
}
function loadingHide() {
$("#overlay_loading").hide();
$("body").css("overflow", "inherit")
}
function getData() {
var e = $("body").data("dats")
}
function reloadThumbs(e) {
if (!cropping) {
var t = $($("#object_layers li").get().reverse());
if (e) {
var n = [];
var r = getIndex(e);
n[r] = e
} else {
var n = c.getObjects();
var i = "";
if (n.length !== t.length) {
$("#object_layers").empty();
for (var s = 0; s < n.length; s++) {
var o = $('<image width="120" height="75" />').attr("src", i);
$("<li/>").prependTo("#object_layers").append(o)
}
t = $($("#object_layers li").get().reverse())
}
}
for (s in n) {
if (n[s] !== undefined) {
var u = fabric.document.createElement("canvas");
if (!u.getContext && typeof G_vmlCanvasManager != "undefined") {
G_vmlCanvasManager.initElement(u)
}
u.width = $("#cc").width();
u.height = $("#cc").height();
fabric.util.wrapElement(u, "div");
var a = new fabric.Canvas(u);
a.backgroundColor = "transparent";
var f = n[s].isActive();
a.add(n[s]);
a.renderAll();
var i = a.toDataURLWithMultiplier("png", .35101058);
if (f) {}
$(t.get(s)).find("img").attr("src", i);
$("#object_layers li").click(function () {
$("#object_layers li").removeClass("layer_selected");
$(this).addClass("layer_selected")
})
}
}
reloadData()
}
}
function reloadLayers() {
$($("#object_layers li").get().reverse()).each(function () {
if ($(this).data("object") !== undefined) c.bringToFront($(this).data("object"))
});
reloadData()
}
function reloadData() {
var e = c.getObjects();
var t = $($("#object_layers li").get().reverse());
for (var n in e) {
if (e[n] !== undefined) {
$(t.get(n)).data("object", e[n])
}
}
c.selection = false
}
function cropStart() {
cropping = true;
c.forEachObject(function (e) {
e.selectable = false
});
var e = actObj;
var t = {
left: 450,
top: 150,
width: 300,
height: 200
};
console.log(t);
cropObject = new Crop({
left: t.left,
top: t.top,
fill: "rgba(255,255,255,0)",
width: t.width,
height: t.height
});
c.add(cropObject);
c.deactivateAll();
cropObject.selectable = true;
c.setActiveObject(cropObject);
c.bringToFront(cropObject);
c.renderAll();
$("#crop_control").show()
}
function crop() {
var e = cropObject.width * cropObject.scaleX;
var t = cropObject.height * cropObject.scaleY;
var n = cropObject.left - e / 2;
var r = cropObject.top - t / 2;
var i = actObj;
i.clone(function (s) {
var o = fabric.document.createElement("canvas");
if (!o.getContext && typeof G_vmlCanvasManager != "undefined") {
G_vmlCanvasManager.initElement(o)
}
o.width = e;
o.height = t;
fabric.util.wrapElement(o, "div");
var u = new fabric.Canvas(o);
u.backgroundColor = "transparent";
s.setOpacity(1);
u.add(s);
s.left -= n;
s.top -= r;
u.renderAll();
var a = u.toDataURL();
var f = $("<img src=" + a + " />").get(0);
i.scaleX = 1;
i.scaleY = 1;
i.setElement(f);
i.width = e;
i.height = t;
i.setAngle(0);
c.setActiveObject(i);
c.renderAll();
setTimeout(function () {
c.renderAll();
reloadThumbs(i)
}, 100);
reloadThumbs()
});
cropFinish()
}
function cropFinish() {
$("#crop_control").hide();
$(".ct").removeAttr("disabled");
$("#object_layers").sortable("enable");
cropping = false;
c.remove(cropObject);
cropObject = null
}
var cropping = false;
var c = new fabric.Canvas("cc");
var start, set = "personal";
c.setOverlayImage("img/foreground-personal.png", c.renderAll.bind(c));
c.backgroundColor = "rgba(59,89,152,1)";
$(function () {
if (window.File && window.FileReader && window.FileList && window.Blob) {} else {}
$("#fileupload").fileupload({
add: function (e, t) {
if (typeof FileReader !== "undefined") {
$(t.files).each(function (e) {
var t = this;
var n = new FileReader;
n.onload = function (e) {
var t = e.target.result;
fabric.Image.fromURL(t, function (e) {
if (e.getWidth() > 800) {
e.scaleToWidth(800)
}
if (e.getHeight() > 400) {
e.scaleToHeight(400)
}
c.add(e);
e.setActive(true);
c.centerObjectH(e).centerObjectV(e);
e.setCoords();
c.renderAll();
var n = $('<image width="120" height="55" />').attr("src", t);
$("<li/>").prependTo("#object_layers").append(n);
reloadThumbs()
})
};
n.readAsDataURL(t)
})
} else {
t.submit()
}
},
dataType: "json",
done: function (e, t) {
$.each(t.result, function (e, t) {
$("<p/>").text(t.name).appendTo(document.body);
fabric.Image.fromURL(t.url, function (e) {
var t = e.set({
left: 110,
top: 75
}).scale(.7);
c.add(t).renderAll()
})
})
}
});
$(document).keydown(function (e) {
if (e.which == 46 && !cropping) {
var t = c.getActiveObject();
if (t) {
c.remove(t);
reloadThumbs()
}
}
});
$("#save").click(function () {
var e = JSON.stringify(c);
loadingShow("Saving... Please Wait...");
$.ajax({
type: "POST",
url: "ajax.php",
data: {
d: e
}
}).done(function (e) {
loadingHide();
alert("Data Saved!")
})
})
});
c.observe("object:modified", function (e) {
reloadThumbs(e.target)
});
c.observe("object:selected", function (e) {
var t = e.target;
var n = getIndex(t);
if (t.type == "image") {
$(".ot").attr("disabled", "disabled").val("");
$(".oi").removeAttr("disabled")
} else if (t.type == "text") {
$(".oi").attr("disabled", "disabled");
$(".ot").removeAttr("disabled");
var r = t.toObject();
var i = t.getFill();
if (start && r.text == "Click here to start") {
c.clear();
reloadThumbs();
start = false
}
$("#text_text").val(r.text);
$("#text_color").val(i.toUpperCase());
$("#text_font").val(r.fontFamily)
}
});
c.observe("selection:cleared", function (e) {
$(".ot").val("").attr("disabled", "disabled");
$(".oi").val("").attr("disabled", "disabled")
});
var cropObject = null;
var actObj;
$("#image_crop").click(function () {
$(this).attr("disabled", "disabled");
$(".ct").attr("disabled", "disabled");
$("#object_layers").sortable("disable");
actObj = c.getActiveObject();
cropStart();
return false
});
$("#crop_ok").click(function () {
crop();
c.forEachObject(function (e) {
e.selectable = true
})
});
$("#crop_cancel").click(function () {
cropping = false;
cropFinish();
c.setActiveObject(actObj);
c.forEachObject(function (e) {
e.selectable = true
});
return false
})
this is the save code in js using ajax
$("#save").click(function () {
var e = JSON.stringify(c);
loadingShow("Saving... Please Wait...");
$.ajax({
type: "POST",
url: "ajax.php",
data: {
d: e
}
}).done(function (e) {
loadingHide();
alert("Data Saved!")
})
})
});
this my php file
echo $_POST['e'];
echo json_decode($_POST['e']);
echo var_dump(json_decode($_POST['e']));
$name=time();
file_put_contents("uploads/" . $name . ".png", $data);
Your posted data has a key d but you are trying to read from e which doesn't have a value.
Even if that wasn't the case, then I'm pretty sure that no valid JSON data will decode to be a PNG binary anyway.
I am trying to pass dynamic data from mysql then creating multiple markers on google.
Here is my html code.
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div class="map">
<div id="map" style="width: 100%;height:738px;"></div>
</div>
</div>
Here is the angularjs Script.
//Angular App Module and Controller
var investup = angular.module('mapsApp', [])
investup.controller('MapCtrl', function ($scope, $compile) {
var cities = [
{
title: 'xyz',
city : '<img src="images/xxx.jpg" />',
lat : 12.2917925,
long : 76.6704174
},
{
title: 'Add to Cart',
city : '<button class="org-btn" ng-click="cartone()" style="display:block;font-size:12px;margin:0 auto 0 auto;">Add to Cart</button>',
lat : 12.2725645,
long : 76.6705986
},
];
//Define your locations: HTML content for the info window, latitude, longitude
var popup = [
['<img src="images/xyz.jpg" />'],
['<img src="images/xyz.jpg"/>'],
];
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [iconURLPrefix + 'red-dot.png', iconURLPrefix + 'purple-dot.png']
var iconsLength = icons.length;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(12.2982778, 76.6903664),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
}
$scope.popup = popup;
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var activeInfoWindow;
var activeInfoWindow2;
var iconCounter = 0;
$scope.markers = [];
for (i = 0; i < cities.length; i++) {
var createMarker = function (info) {
var marker = new google.maps.Marker({map: $scope.map,icon: icons[iconCounter],position: new google.maps.LatLng(info.lat, info.long),popup: popup[i][0]});
google.maps.event.addListener(marker, 'click', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
var contentString = "<div><h2>" + info.city + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow = infoWindow;
});
google.maps.event.addListener(marker, 'mouseover', function() {
var contentString = "<div><h2>" + marker.popup + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow2 = infoWindow;
if(activeInfoWindow != null)
activeInfoWindow.close();
});
google.maps.event.addListener(marker, 'mouseout', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
});
$scope.markers.push(marker);
}
createMarker(cities[i]);
iconCounter++;
}
$scope.openInfoWindow = function(e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Here is the screenshot of the result
This is the static code when i'm placing php code in cities and popup section to not showing the result.
Problem is when i don't how to call php code in angularJS. Kindly help me.
Thanks in advance.
1- You probably would need to use a framework to handle JSON serialization for you.
For the sake of simplicity you can use this library (https://github.com/mevdschee/php-crud-api), and copy api.php to the server root directory.
2- Using $http:
investup.controller('MapCtrl', function($scope, $compile, $http) {
$http.get('/api.php/cities').success(function(response) {
var cities = response.cities;
// the rest of controller function body
}).catch(handleError);
})