Angular-google-maps not displaying map - javascript

I am new to Angular and loving it. I have been diving deeper and being successful until this particular depth.
I forked a workable code which largely meets my needs from (http://kcy.me/1bbra).
Everything works fine. However the maps doesn't display. I went into chrome's console to debug and everything seems fine. The maps is loading and responding to the buttons but not displaying.
After many of hours of debugging, i found out that when i initialized my session the maps doesn't display, when i comment out the session code, everything works fine.
See my code here
This is the code on my dashboard
<?php
require '../scripts/master.php';
$logs = new authenticate();
$logs->page_protect();
//just collecting data from specified table
$rows = $logs->getFilteredDetails("user_info","app_id",$_SESSION['my_user_id']);
//assessing individual records
$my_user_id = $rows['user_id'];
?>
The page protect function from the authenticate class
function page_protect()
{
session_start();
if (!isset($_SESSION['my_user_id']))
{
header("Location: ../login.php");
}
}
This is the section which displays the maps on my dashboard page
<section class="content">
<div ng-controller="MapCtrl">
<div class="map_container">
<google-map center="map.center" zoom="map.zoom" draggable="true" options="map.options" control="map.control">
<markers models="map.markers" coords="'self'" options="'options'" isLabel='true'>
</markers>
</google-map>
</div>
<div class="controls">
<h3>Current location</h3>
<p>
<button ng-click="addCurrentLocation()">Current location</button>
</p>
<h3>Address search</h3>
<p>
<input type="text" placeholder="Address. i.e: Concha Espina 1, Madrid" ng-model="address" style="width: 210px"/>
<button ng-click="addAddress()">Look up!</button>
</p>
<p>
Source Code
</p>
</div>
</div>
</section>
And finally, the angular code
var app = angular.module('AngularGoogleMap', ['google-maps']);
app.factory('MarkerCreatorService', function () {
var markerId = 0;
function create(latitude, longitude) {
var marker = {
options: {
animation: 1,
labelAnchor: "28 -5",
labelClass: 'markerlabel'
},
latitude: latitude,
longitude: longitude,
id: ++markerId
};
return marker;
}
function invokeSuccessCallback(successCallback, marker) {
if (typeof successCallback === 'function') {
successCallback(marker);
}
}
function createByCoords(latitude, longitude, successCallback) {
var marker = create(latitude, longitude);
invokeSuccessCallback(successCallback, marker);
}
function createByAddress(address, successCallback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
var latitude = firstAddress.geometry.location.lat();
var longitude = firstAddress.geometry.location.lng();
var marker = create(latitude, longitude);
invokeSuccessCallback(successCallback, marker);
} else {
alert("Unknown address: " + address);
}
});
}
function createByCurrentLocation(successCallback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var marker = create(position.coords.latitude, position.coords.longitude);
invokeSuccessCallback(successCallback, marker);
});
} else {
alert('Unable to locate current position');
}
}
return {
createByCoords: createByCoords,
createByAddress: createByAddress,
createByCurrentLocation: createByCurrentLocation
};
});
app.controller('MapCtrl', ['MarkerCreatorService', '$scope', function (MarkerCreatorService, $scope) {
MarkerCreatorService.createByCoords(40.454018, -3.509205, function (marker) {
marker.options.labelContent = 'Autentia';
$scope.autentiaMarker = marker;
});
$scope.address = '';
$scope.map = {
center: {
latitude: $scope.autentiaMarker.latitude,
longitude: $scope.autentiaMarker.longitude
},
zoom: 12,
markers: [],
control: {},
options: {
scrollwheel: false
}
};
$scope.map.markers.push($scope.autentiaMarker);
$scope.addCurrentLocation = function () {
MarkerCreatorService.createByCurrentLocation(function (marker) {
marker.options.labelContent = 'You´re here';
$scope.map.markers.push(marker);
refresh(marker);
//alert("I reached");
});
};
$scope.addAddress = function() {
var address = $scope.address;
if (address !== '') {
MarkerCreatorService.createByAddress(address, function(marker) {
$scope.map.markers.push(marker);
refresh(marker);
});
}
};
function refresh(marker) {
$scope.map.control.refresh({latitude: marker.latitude,
longitude: marker.longitude});
}
}]);

Related

google map location search issue

I am working on core PHP, i wants to fecth location based record.
i want exact search for google map,like if i search (implemented autocomplete search) for (BTM layout) means BTM layout google map should come how will do this please help any one.
Here is my HTML form:
<form action="pglist.php" id="location_search" class="form-inline" method="POST" >
<div class="form-group keyword">
<input id="locationTextField" name= "list" type="text" size="50">
<button type="submit" name="filter"><img src="assets/images/search.png" alt="Rentozy" /></button>
</div>
</form>
Here is my database query:
$locations=array();
$query = $conn->query('SELECT `pg_address` FROM `tbl_master_property`');
while ($row = $query->fetch_assoc()) {
$locations[] = $row['pg_address'];
}
$locations = json_encode($locations);
Here my google map script code:
<div class="map">
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyBAM5Cs2VsrOBs8Idqy0t0o6vw4hEU0Lys">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(12.9716, 77.5946);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
animation: google.maps.Animation.DROP,
draggable: true,
map: map,
});
marker.addListener('click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = <?= $locations ?>;
console.log(locations);
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'BTM layout'}, function(results, status) {
if (status === 'OK') {
Map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
You could request the location using geocoder and handle exceptions.

HTML - Javascript - Combine Geocoding and Nearby Search

I am trying to combine Google Geocoding and Nearby Search in one Searchbox.
The user will type his address and the map should show all Bars near him.
initmap Function:
function initMap() {
var setMap = new google.maps.LatLng(50, 9398252, 6.93936825);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: setMap
});
var request = {
location: setMap,
radius: '5000',
types: ['bar']
};
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}
This is my geocode function:
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
This is how I would create Marker:
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
And here is what my search box looks like:
<form class="navbar-form navbar-left">
<div class="form-group">
<div id="floating-panel">
<input id="address" type="textbox" value="Cologne, Germany" class="form-control">
<input id="submit" type="button" value="Search" class="form-control">
</div>
</div>
</form>
Until now I can search for a address, so my geocoder should work.
I just don't know how to involve the nearby search process in my code..
Hopefully somebody can help me with my problem.
Once you receive the result of the Geocoding API, you can call the PlacesService API. Knowing that every call to the API will be async, you'll have to wait for the Geocoding callback to launch the PlaceService API.
It will look like:
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
var service;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
service = new google.maps.places.PlacesService(resultsMap);
service.nearbySearch({ location: results[0].geometry.location, radius: 500, type: [ 'bar' ] }, PlaceServiceCallBack); // where PlaceServiceCallBack handles the markers creation
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

Google Map API not plotting array of markers

I need some advice or a telling off because my code is wrong. I'm new to JQuery and google maps api. I have a JSON get to retrieve my data. I have declared an array and stored (hopefully this is the correct way to do this).
update** - Thanks to #geocodezip I have updated my code to allow correct population of array.
When I run my application the map loads fine but no markers.
I have changed my Google maps initializeMap() to the asynchronous version
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
My array in console.log image
I now have an array populated, but still no markers on my map.
This is my whole script. Maybe there are some major flaws.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//define variables
var geocoder;
var citylat = 0;
var citylng = 0;
var carparksArray = [];
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction()
{
alert("Geocoder failed");
}
function initialize()
{
geocoder = new google.maps.Geocoder();
}
//get city of current location and runs codeAddress()
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ latLng: latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "postal_town") {
itemPostalTown = address_component.address_components[0].long_name;
document.getElementById("town").value = itemPostalTown;
codeAddress();
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
//get latlong of city and runs getCarParks()
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("town").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
citylat = results[0].geometry.location.lat();
citylng = results[0].geometry.location.lng();
getCarParksLatLng();
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//sets map up
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
//loads map
function loadScript() {
var script = document.createElement("script");
script.src = "http://maps.googleapis.com/maps/api/js?callback=initializeMap";
document.body.appendChild(script);
}
//get carparks names
function getCarParksLatLng() {
var town = document.getElementById("town").value;
var carparkList = "<p>";
var uri = "http://localhost/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
});
loadScript();
}
$(document).ready(initialize)
</script>
You are not adding the entries to the carparkArray correctly. Each array element needs to be an array, so the array looks like this:
var carparksArray = [
['Bondi Beach', -33.890542, 151.274856, 4],
// ...
];
updated code:
var carparks = [];
$.getJSON(uri,
function (data) {
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparks.push([val.Name, val.Latitude, val.Longitude]);
});
});
loadScript();
}
proof of concept fiddle
Thanks for everyone's help on this. Because #geocodezip stated that
$.getJSON is asynchronous I moved my loadscript() function call inside the getJSON function and it now plots the map points.
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
loadScript();
});

Connecting Direction Service in Angular

I've set up a map using AngularJS. The marker data is from a json file and is in working order. But I'd like the user to be able to click on a button (either from the item list or in the info window) to get directions from their current location to their selected destination.
I do not know how to connect Google Maps Direction Service to what I have. The current function is connected to the button in the marker list, not the info window. But I would like the direction service to work in either.
Any and all help is much appreciated. Thanks!
Here is the site (all source code is available) http://portlandstreetcarbars.com/streetcar-bars-map/app/#/
Here is the HTML:
<h3>Click on a bar below to view its location or get directions.</h3>
<div class="horizontal">
<div class="table">
<article class="list-group-item" id="class" ng-repeat="marker in markers | orderBy : 'title'">
<a href="#" ng-click="openInfoWindow($event, marker)">
<div class="img-wrap">
<img id="bar-image" class="bar-image" src={{marker.image}} />
<!-- End Image Gallery -->
</div>
<h3 class="box-title">{{marker.title}}</h3>
</a>
<input type='button' ng-click='getDirections(marker)' value='Get directions'>
</article>
</div>
</div>
<h3 class="map">Click on a marker below to view its location or get directions.</h3>
<section class="map-container">
<div id="map"></div>
<h3>Directions Go here</h3>
<div id="panel">
<input type='button' id="reset-map" ng-click='clearMarkers()' value='Reset Map'>
</div>
</section>
Here is the script:
var mapApp = angular.module('mapControllers', []);
mapApp.controller('ListController', function ($scope, $http) {
$http.get('scripts/bars.json').
success(function(data, status, headers, config) {
$scope.bars = data;
var myLatlng100 = new google.maps.LatLng(45.522535,-122.659492);
var mapOptions = {
center: myLatlng100,
zoom: 15,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (bar){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(bar.lat, bar.lng),
title: bar.name
});
marker.content = '<div class="contentString"><img src="' +
bar.image +
'"><br/>'+
bar.address +
' '+
bar.city +
', '+
bar.state +
'<button ng-click="getDirections('+bar.lat+', '+bar.lng+')">Get Directions</button>' +
'</div>';
marker.image = bar.image;
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('' +'<h2 class="info-window">' + bar.name + '</h2>' + '' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
var i;
for (i = 0; i < $scope.bars.length; i++){
createMarker($scope.bars[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
};
$scope.getDirections= function(marker) {
$scope.marker = marker;
$scope.lat = $scope.marker.position.D;
$scope.lng = $scope.marker.position.k;
console.log($scope.lat);
if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) { //This gets the
var latitude = position.coords.latitude; //users current
var longitude = position.coords.longitude; //location
var start = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap($scope.map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: start,
destination: new google.maps.LatLng( $scope.lat, $scope.lng),
travelMode: google.maps.DirectionsTravelMode.TRANSIT
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
} else {
//Browser doesn't support Geolocation
handleNoGeolocation(false);
}
};
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: $scope.map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
}).
error(function(data, status, headers, config) {
console.log("Did not compute");
});
})
I fixed this issue. I had my getDir function incorrectly inside the controller (apparently).
I removed it, added map as a parameter and it works. But the direction path doesn't render on the map. So if anyone has any ideas as to how to fix this...

Directions Service of Google Maps API doesn't work

Do you have any idea why my directions service of Google Maps API doesn't work? It seems that method directionsService.route() isn't executed (cause alert with status is not displayed), but I don't know why. I'm newbie in Google Maps API and JS, so try to be forgiving, if it's something simple. :)
var map = null;
var pos = null;
const STORED_LOC = new google.maps.LatLng(50.405196, 11.894855);
var currentLat = document.getElementById("latLabel");
var currentLng = document.getElementById("lngLabel");
var additionalInfo = document.getElementById("additionalInfo");
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
pos = STORED_LOC;
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
options =
{
center: pos,
zoom: 15
}
marker = new google.maps.Marker(
{
position: pos,
map: map,
title: "Chosen localization"
}
);
map = new google.maps.Map(document.getElementById("mapContainer"), options);
marker.setMap(map);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
}
$("#yes").click(function () {
getPosition();
hideUserConsentSection();
});
$("#no").click(function () {
hideUserConsentSection();
showSetCustomLocationSection();
});
function showSetCustomLocationSection() {
$("#setCustomLocationSection").show();
}
function hideUserConsentSection() {
$("#userConsentSection").hide();
}
function getPosition() {
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 2000
}
navigator.geolocation.getCurrentPosition(showPosition, errorPosition, options);
}
else
{
additionalInfo.innerHTML += "Your browser doesn't support geolocation";
}
}
function showPosition(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
var request =
{
origin: STORED_LOC,
destination: pos,
travelmode: google.maps.TravelMode.DRIVING
}
directionsService.route(request, function(result, status)
{
alert(status);
if (status == google.maps.DirectionsStatus.OK)
{
alert("OKAY");
directionsDisplay.setDirections(result);
}
});
//map = new google.maps.Map(document.getElementById("mapContainer"), options);
//marker.setMap(map);
}
function errorPosition(position) {
switch (position.code) {
case 1:
showSetCustomLocationSection();
break;
case 2:
showSetCustomLocationSection();
break;
case 3:
showSetCustomLocationSection();
break;
default:
break;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
My HTML looks like that:
<h3>How to reach us?</h3>
<div id="userConsentSection">Can we use your geolocation?<br />
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" /><br /><br />
</div>
<div id="setCustomLocationSection" style="display:none">
Enter your geolocation. <br /><br />
<input type="text" id="customLocation" />
<input type="button" id="setCustomLocationButton" value="Show" /><br /><br />
</div>
<span>Latitude: </span>
<div id="latLabel">
</div>
<span>Longitude: </span>
<div id="lngLabel">
</div>
<div id="additionalInfo">
</div>
<div id="mapContainer" style="height: 400px; width: 100%">
</div>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=XXXX&sensor=true">
</script>
The answer is typo in request object - travelmode instead travelMode. This parameter is required and as the result - route method doesn't execute. Be careful with that name!

Categories

Resources