I'm trying to create a service in which I get a list of sites and the ability to share that data between controllers
angular.module('app')
.controller('googleMapCtrl', ['$scope', function($scope ){
var map;
$scope.placeNameArr = [];
console.log($scope.placeNameArr);
function initialise (position) {
$scope.$apply(function(){
var center = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'),{
center: center,
zoom:12
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(),
new google.maps.LatLng());
var option = {
bounds: defaultBounds,
types: ['(cities)']
};
var input = document.getElementById('pac-input');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input, option) ;
var request = {
location: center,
radius: 8047,
types: [ 'restaurant' ]
// 'restaurant'
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
})
}
function callback(results, stattus) {
if(stattus == google.maps.places.PlacesServiceStatus.OK) {
for (var i=0; i < results.length; i++) {
var place = results[i]
createMarker(results[i]);
// console.log(results);
}
$scope.$apply(function () {
$scope.places = results;
});
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
photos = place.photos;
if (!photos) {
return;
}
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
'<img src='+ place.photos[0].getUrl({'maxWidth': 175, 'maxHeight': 175}) +'>' + '<br>' + 'Rating:' + place.rating + '<img src='+ place.photos +'>' + '</div>');
infowindow.open(map,this);
})
console.log(place);
$scope.placeNameArr.push(place.name);
}
navigator.geolocation.getCurrentPosition(initialise);
// google.maps.event.addDomListener(window, 'load', initialize);
}])
I I'm not sure what approach i should take in this problem.
Ultimately i would like to share this results with Wikipedia API Controller
angular.module('app')
.controller('wikiCtrl', ['$scope','$http', function($scope, $http ){
var vm = $scope;
vm.searchTermArr = [];
vm.searchWiki = function(wikiFactory){
console.log(response);
}
vm.searchWiki = function(){
$http({
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + vm.searchTerm + '&format=json&callback=JSON_CALLBACK',
method: 'jsonp'
}).success(function(response){
console.log(response);
vm.searchTermArr.push(response[1]);
vm.searchTermArr.push(response[2]);
vm.searchTermArr.push(response[3]);
});
};
}]);
and get information based of long name of location ....
Thank you for all your suggestions.
Related
Hello guys I need help from you. I'm coding a web application using laravel framework. I've recorded logitudes, latitudes and other informations in the database. I want to fetch those informations and display their marker on google map. All examples I'm getting are for PHP scratch code. Is there anyone who can help me how to do it in laravel?
HERE IS THE DATABASE CODE
Schema::create('alertes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->string('code_client');
$table->string('client_category');
$table->string('longitude');
$table->string('latitude');
$table->timestamps();
});
HERE IS MY BLADE FILE
<div id="map" style="width:100%;height:400px;"></div>
</div>
</div>
</div>
</div>
#endsection()
#section('custom-script')
<script type="text/javascript" src="{{asset('assets')}}/map/carte_alertes.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnyJJ2gorvX0rsuhBJLNUsfyioWSSep2Q&callback=init"></script>
<script>
</script>
#endsection
HERE IS MY SCRIPT.JS
<script>
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Beni
var center = new google.maps.LatLng(0.496422, 29.4751);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
makeRequest("{{route('alertes.index')}}", function (data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
// displayLocation method
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.code_client + '</strong>'
+ '<br/>' + location.client_category + '</div>';
if (parseInt(location.latitude) == 0) {
geocoder.geocode({'client_category': location.client_category}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
change callback=initMap not callback=init
src="https://maps.googleapis.com/maps/api/js?key=yourapikey&callback=init"></script>
try your data format this way
public function mapMarker(){
$locations = Alerte::all();
$map_markes = array ();
foreach ($locations as $key => $location) {
$map_markes[] = (object)array(
'code' => $location->code,
'code_client' => $location->code_client,
'client_category' => $location->client_category,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
);
}
return response()->json($map_markes);
}
copy this code and re-place this code
content : `<div><h5>${Number(datas[index].latitude)}</h5><p><i class="icon address-icon"></i>${Number(datas[index].longitude)}</p></div>`
Still having the problem
HERE IS MY NE
function initMap(){
var mapElement = document.getElementById('map');
var url = '/map-marker';
async function markerscodes(){
var data = await axios(url);
var alerteData = data.data;
mapDisplay(alerteData);
}
markerscodes();
function mapDisplay(datas) {
//map otions
var options ={
center :{
lat:Number(datas[0].latitude), lng:Number(datas[0].longitude)
},
zoom : 10
}
//Create a map object and specify the DOM element for display
var map = new google.maps.Map(mapElement, options);
var markers = new Array();
for (let index = 0; index < datas.length; index++){
markers.push({
coords: {lat: Number(datas[index].latitude), lng:Number(datas[index].longitude)},
content : '<div><h5>${datas[index].code_du_suspect}</h5><p><i class="icon address-icon"></i>${datas[index].etat_du_suspect}</p></div>'
})
}
//looping through marker
for (var i = 0; i < markers.length; i++){
//une fontion a creer si dessous
addMarker(markers[i]);
}
function addMarker(props){
var marker = new gooogle.maps.Marker({
position : props.coords,
map: map
});
if(props.iconImage){
marker.setIcon(props.iconImage);
}
if(props.content){
var infoWindow = new google.maps.infoWindow({
content : props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
}
}
}
I am using angularjs for my application.I am trying to load the address from user_address table in database and display it on map on load.
Here is the script i am using to load google maps
<script async defer src="https://maps.googleapis.com/maps/api/js?
key=myKey&callback=initMap">
</script>
Here is the html
<div id="map"></div>
<div id="repeatmap" data-ng-repeat="marker in markers | orderBy :
'title'">
<a id="country_container" href="#" ng-
click="openInfoWindow($event, marker)">
<label id="namesformap" >{{marker.title}}</label></a>
</div>
Here is the Controller.js
var DirectoryController = function($scope, $rootScope, $http,
$location, $route,DirectoryService,HomeService,$routeParams)
{
$scope.getAllCities = function()
{
DirectoryService.getAllCities().then(function(response){
$scope.cities = response.data;
console.log($scope.cities);
})
}
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25,80),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'),
mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc +
'</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (var i = 0; i < $scope.cities.length; i++){
createMarker($scope.cities[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
}
In getAllCities function i am getting response from database that is all the names of cities.
As you can see in console i am able to get the response from database but i am not able to get $scope.cities value to for loop.It is saying Cannot read property 'length' of undefined.Can anyone tell how can i get value of $scope.cities into for loop so that in map i can display the cities returned from database.Now i am able to display map but with no cities and no markers.I dont know whether it will work or not or am i doing the wrong way?
This is most likely because you're trying to add the markers before the request to the database has finished resolving. This happens because the database/webservice request is most likely executed asynchronously.
Instead run the code for setting up the markers, when your promise from the database request have resolved. Like this:
var DirectoryController = function($scope, $rootScope, $http, $location, $route,DirectoryService, HomeService, $routeParams)
{
$scope.getAllCities = function()
{
DirectoryService.getAllCities().then(function(response){
$scope.cities = response.data;
console.log($scope.cities);
setupMapMarkers();
});
}
function setupMapMarkers(){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25,80),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < $scope.cities.length; i++){
createMarker($scope.cities[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
}
function createMarker(info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
}
I am building a GoogleMap with multiple markers with infowindows attached. I have tried to build this into a re-usable Javascript Class using prototypes but my infowindows will not open (the markers show up fine).
If I test console.log within the click event listener it triggers, but the infowindows themselves refuse to open.
Markers.json is just a JSON object which returns a list of data to be looped through.
JS Fiddle
I am initiating the map using:
$(document).ready(function(){
var customMap = new CustomMap('mapitems');
customMap.init();
customMap.setMarkers();
});
My Javascript:
function CustomMap(mapId, defaultLat, defaultLng, defaultZoom)
{
this.map = null;
this.markerBounds = null;
this.$mapContainer = document.getElementById(mapId);
this.defaultLat = (defaultLat ? defaultLat : '-36.848460');
this.defaultLng = (defaultLng ? defaultLng : '174.763332');
this.defaultZoom = (defaultZoom ? defaultZoom : 15);
}
CustomMap.prototype.init = function() {
var position = new google.maps.LatLng(this.defaultLat, this.defaultLng);
this.map = new google.maps.Map(this.$mapContainer, {
scrollwheel: true,
mapTypeId: 'roadmap',
zoom: this.defaultZoom,
position: position
});
this.markerBounds = new google.maps.LatLngBounds();
};
CustomMap.prototype.setMarkers = function() {
var that = this;
$.get('/locations.json', null, function(locations) {
for (var i = 0; i < locations.length; i++) {
that.processMarker(locations[i]);
}
that.map.fitBounds(that.markerBounds);
}, 'json');
};
CustomMap.prototype.processMarker = function(data) {
if (data.lat && data.lng) {
var position = new google.maps.LatLng(data.lat, data.lng);
this.markerBounds.extend(position);
var marker = this.getMarker(position);
this.setInfoWindow(marker, data);
}
};
CustomMap.prototype.getMarker = function(position) {
return new google.maps.Marker({
map: this.map,
draggable:false,
position: position
});
};
CustomMap.prototype.setInfoWindow = function(marker, data) {
var that = this;
marker.infoWindow = new google.maps.InfoWindow({
content: that.buildInfoHtml(data)
});
google.maps.event.addListener(marker, 'click', function() {
marker.infoWindow.open(that.map, marker);
});
};
CustomMap.prototype.buildInfoHtml = function(data) {
var html = '';
html += '<strong>' + data.title + '</strong><br>';
if (data.address.length > 0)
html += data.address + '<br>';
if (data.freephone.length > 0)
html += 'Freephone: ' + data.freephone + '<br>';
if (data.depotPhone.length > 0)
html += 'Depot Phone: ' + data.depotPhone + '<br>';
if (data.hours.length > 0)
html += 'Depot Hours: ' + data.hours + '<br>';
return html;
};
I'm using the Google Places JavaScript API for a desktop application. However, the search results returned by the API aren't the same as the ones I get in maps.google.com. For instance, if I search for "Antique Hostel", I get many results (almost all of them are kinda random) whereas on Google Maps I get the correct (single) result.
Is the quality of the search isn't the same in the API and the service?
Here is my code
function initialize() {
// map setup
var mapOptions = {
center: new google.maps.LatLng(52.519171, 13.406091199999992),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
$map = document.getElementById('mapCanvas'),
map = new google.maps.Map($map, mapOptions),
input = document.getElementById('searchInput'),
autocomplete = new google.maps.places.Autocomplete(input),
service = new google.maps.places.PlacesService(map),
$ajaxSearchInput = $(input),
markers = [];
autocomplete.bindTo('bounds', map);
$ajaxSearchInput.keydown(function(e) {
if (e.keyCode === 13) {
var request = {
query: $(this).val(),
radius: '500',
location: map.getCenter()
}
service.textSearch(request, searchCallBack);
}
});
searchCallBack = function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
console.log(results);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i], bounds);
}
map.fitBounds(bounds);
}
}
createMarker = function(place, bounds) {
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
// event listener to show the InfoWindow.
(function(marker, place) {
google.maps.event.addListener(marker, 'click', function() {
var content = '<h3>' + place.name + '</h3> ' + place.formatted_address + '<br>',
infowindow = new google.maps.InfoWindow({
content: ''
});
if (place.rating) {
content += '<p> <b>Rating</b>: ' + place.rating + '</p>';
}
if (place.types) {
content += '<p> <b>Tags</b>: ';
for (var j = 0, tag; tag = place.types[j]; j++) {
content += tag + ', '
}
content += '</p>';
}
infowindow.content = content;
infowindow.open(map, marker);
});
})(marker, place);
markers.push(marker);
bounds.extend(place.geometry.location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I'm trying to develop a page using different scripts like google places autocomplete, the query with checkboxes (https://developers.google.com/fusiontables/docs/samples/in) and zooming on a place (http://www.geocodezip.com/v3_FusionTables_GViz_zoom2MarkerA.html).
The thing is, the autocomplete or checkboxes+zoom work fine on their own, but everything's wrong when combined!
I've tried to dislocate the code and re-assemble, but it doesn't work and I don't understand why.
I'm a total beginner in Javascript so I'm really testing and adapting things.
Many thanks if you have any clues!
The code with checkboxes + zoom:
// Checkboxes
layer = new google.maps.FusionTablesLayer();
filterMap(layer, FT_TableID, map);
google.maps.event.addDomListener(document.getElementById('0'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('1'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('2'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('3'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
google.maps.event.addDomListener(document.getElementById('4'),
'click', function() {
filterMap(layer, FT_TableID, map);
});
}
// Filter the map based on checkbox selection.
function filterMap(layer, FT_TableID, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: 'Latitude',
from: FT_TableID,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var stores = document.getElementsByName('note');
for (var i = 0, note; note = stores[i]; i++) {
if (note.checked) {
var noteName = note.value.replace(/'/g, '\\\'');
filter.push("'" + noteName + "'");
}
}
var where = '';
if (filter.length) {
where = "'coeurs' IN (" + filter.join(',') + ')';
}
return where;
}
google.maps.event.addDomListener(window, 'load', initialize);
///// end of checkboxes part
//////// zoom
function changeQuery(term) {
layer.setOptions({query:{select:'Latitude', /* was 'Latitude,Longitude', used to work... */
from:FT_TableID,
where:"'Nom' contains ignoring case '"+term + "'"
//à la place de : where:"Nom contains "+term
}
});
// alert("query="+term);
// zoom and center map on query results
//set the query using the parameter
var queryText = encodeURIComponent("SELECT 'Latitude', 'Longitude' FROM "+FT_TableID+" WHERE 'Nom' contains '"+term+"'");
// does _not_ work var queryText = encodeURIComponent("SELECT 'Latitude' FROM "+FT_TableID+" WHERE District = "+term);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(zoomTo);
}
function zoomTo(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var bounds2 = new google.maps.LatLngBounds();
for(i = 0; i < numRows; i++) {
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 0)),
parseFloat(response.getDataTable().getValue(i, 1)));
bounds2.extend(point);
}
// zoom to the bounds
map.fitBounds(bounds2);
map.setZoom(18);
}
The code used for the autocomplete:
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// 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(16); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(O, 0),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [
(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 || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
google.maps.event.addDomListener(window, 'load', initialize);
there are two calls of initialize:
google.maps.event.addDomListener(window, 'load', initialize);
remove one of them.