How to Auto Fill my current address to a search box - google-maps

Greeting, I'm new to IONIC and now i have met a problem. I'm trying to include a google map direction services in my application. The application now will jump to the location A once i input the address in the search box, but what i want is when i 1st open the app, search box A will automatically get my location address and fill the address in the textbox A.
TaxiServices.html
<div class="bar bar-header bar-dark item item-button-left">
<!--<a class="button icon-left ion-chevron-left button-clear button-dark" ng-click="st.link()">Home Page</a>-->
<button class="button button-clear" ng-click="ts.link()">
<i class="icon ion-arrow-left-c"></i>
</button>
<h1 class="title">Taxi Services TEST</h1>
</div>
<ion-view ng-app="taxiservice" ng-controller="MapController">
<ion-content class="has-footer has-header" scroll="false">
<div class="container">
<div class="titlebar">
<div class="preorder">
<!--http://jsfiddle.net/ucmL2/-->
<ion-checkbox ng-model="ModelData.Animals">Pre-Order</ion-checkbox>
<div class="form-group" ng-show="ModelData.Animals">
<form action="action_page.php">
Date & Time :
<input type="datetime-local" class="datetime">
</form>
</div>
</div>
<div class="places">
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
</div>
</div>
<div id="map" data-tap-disabled="true"></div>
<div class="fare has-footer">
<h3>Estimated Fare: </h3>
</div>
</div>
taxiservice-ctrl.js
var map;
(function () {
'use strict';
angular
.module('taxiservice.ctrl', [])
.controller('TaxiServiceCtrl', ['$scope', '$ionicPopup', '$timeout', '$rootScope', '$interval', '$window', '$ionicLoading',
function ($scope, $ionicPopup, $timeout,$rootScope, $interval, $window, $ionicLoading) {
//variables
var self = this;
self.link = link;
function link() {
$window.location.href = "../../js/ServiceMenu/index.html";
}
$scope.showPopup = function() {
var alertPopup = $ionicPopup.alert({
title: 'Good News!',
template: 'Yay! We have found you a driver!'
});
alertPopup.then(function(res) {
$window.location.href = "../../js/TaxiFound/index.html";
});
};
}])
.controller('MapController', function ($scope, $ionicLoading) {
google.maps.event.addDomListener(window, 'load', function () {
var origin_place_id = null;
var destination_place_id = null;
var travel_mode = google.maps.TravelMode.WALKING;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 17
});
navigator.geolocation.getCurrentPosition(function (pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
var origin_input = document.getElementById('origin-input');
var destination_input = document.getElementById('destination-input');
var options = {
types: ['geocode'],
componentRestrictions: {country: 'my'}
};
map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
var origin_autocomplete = new google.maps.places.Autocomplete(origin_input, options);
origin_autocomplete.bindTo('bounds', map);
var destination_autocomplete =
new google.maps.places.Autocomplete(destination_input, options);
destination_autocomplete.bindTo('bounds', map);
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function expandViewportToFitPlace(map, place) {
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
}
origin_autocomplete.addListener('place_changed', function() {
var place = origin_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
origin_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
destination_autocomplete.addListener('place_changed', function() {
var place = destination_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
destination_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
function route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay) {
if (!origin_place_id || !destination_place_id) {
return;
}
directionsService.route({
origin: {'placeId': origin_place_id},
destination: {'placeId': destination_place_id},
travelMode: travel_mode
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
});
});
})();
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' *; style-src 'self' 'unsafe-inline' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *">
<title></title>
<link href="../../css/ionic.app.css" rel="stylesheet">
<script src="../../lib/angular/angular.js"></script>
<script src="../../lib/angular-animate/angular-animate.js"></script>
<script src="../../lib/angular-sanitize/angular-sanitize.js"></script>
<script src="../../lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="../../lib/ionic/js/ionic.js"></script>
<script src="../../lib/ionic/js/ionic-angular.js"></script>
</head>
<body ng-app="taxiservice">
<ion-nav-view>
</ion-nav-view>
<script src="https://maps.googleapis.com/maps/api/js?&callback=&libraries=places&sensor=false">
</script>
<script src="app.js"></script>
<script src="map.js"></script>
<script src="content/taxiservice-ctrl.js"></script>
</body>
</html>
app.js
var app = angular
.module('taxiservice', [
'ionic',
'taxiservice.ctrl'
])
.run(function($ionicPlatform,$timeout) {
$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();
}
});
})
.config(function($ionicConfigProvider,$stateProvider,$urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
templateUrl: 'content/TaxiService.html',
controller:'TaxiServiceCtrl as ts'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app');
});
I have struggled with this problem very long times, please help!

Look the reverse geocoding example here. You can retrieve the address by using the position which you already have and then add the marker. https://github.com/mapsplugin/cordova-plugin-googlemaps/wiki/geocoder

A good plugin i use on my app for fill Google Maps Autocomplete is
https://github.com/israelidanny/ion-google-place
Easy to install , reverse geocoding included , Great Template
the customization is easy
Good Luck

Related

Apply google.maps.LatLngBounds() but not working - Ionic

I'm trying to add google maps in my ionic project. Other than that, I want all the markers in google maps fits all in screen. I don't know where it wrong. My reference here https://developers.google.com/maps/documentation/javascript/reference?csw=1#LatLngBounds
Here is the code
HTML: index.html
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&amp</script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script
HTML: home.html
<ion-content>
<map on-create="mapCreated(map)"></map>
</ion-content>
JS: directives.js
angular.module('starter.directives', [])
.directive('map', function() {
return {
restrict: 'E',
scope: {
onCreate: '&'
},
link: function ($scope, $element, $attr) {
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(43.07493, -89.381388),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($element[0], mapOptions);
$scope.onCreate({map: map});
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}
if (document.readyState === "complete") {
initialize();
} else {
google.maps.event.addDomListener(window, 'load', initialize);
}
}
}
});
JS: app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.directives'])
JS: controllers.js
$scope.mapCreated = function (map) {
$scope.map = map;
var pos = new Array (new google.maps.LatLng(3.050511,101.687833), new google.maps.LatLng(3.122847,101.676846), new google.maps.LatLng(3.078409,101.608025), new google.maps.LatLng(2.932928,101.642603));
//Create marker
var createMarker = function (pos, icon) {
console.log("create marker");
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: icon,
});
}
var getAllMarkers = function(){
var bounds = new google.maps.LatLngBounds();
for(var i=0; i<pos.length; i++){
bounds.extend(pos[i]);
createMarker(pos[i], 'https://maps.google.com/mapfiles/ms/icons/red-dot.png');
}
$scope.map.fitBounds (bounds);
}
getAllMarkers();
$scope.map.setCenter(pos[0]);
};
Output from the code: Picture 1
This is the output that I want: Picture 2
I suggest to use ngMap or other Angular-module (for example angular-google-map).
Here is an example:
var app = angular.module('myApp', ['ionic', 'ngMap']);
app.controller('MapCtrl', ['$scope', '$http', '$state', 'NgMap', '$timeout',
function($scope, $http, $state, NgMap, $timeout) {
$scope.zoom = 10;
$scope.cx = {
"latitude": 3.050511, "longitude": 101.687833
};
$scope.pos = [{"lat": 3.050511,"lng": 101.687833},
{"lat": 3.122847,"lng": 101.676846},
{"lat": 3.078409,"lng": 101.608025},
{"lat": 2.932928,"lng": 101.642603}
];
NgMap.getMap().then(function(map) {
$scope.map = map;
});
}])
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Simle Map</title>
<meta name="description" content="Simple Map" />
<meta name="keywords" content="ng-map,AngularJS,center" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<script src="app.js"></script>
<link href="http://code.ionicframework.com/nightly/css/ionic.min.css" rel="stylesheet">
</head>
<body ng-controller="MapCtrl">
<ion-header-bar class="bar-dark">
<h1 class="title">Simple Map in Ionic</h1>
</ion-header-bar>
<ion-content>
<div class="card">
<div class="item item-divider">
NgMap
</div>
<ng-map center="{{cx.latitude}}, {{cx.longitude}}" zoom="{{zoom}}" style="width:100%; height: 100%;">
<marker ng-repeat="p in pos track by $index" position="{{p.lat}}, {{p.lng}}"></marker>
</ng-map>
<pre>cx = {{cx|json}}</pre>
<pre>pos = {{pos|json}}</pre>
</div>
</ion-content>
<ion-footer-bar class="bar-dark">
Footer
</ion-footer-bar>
</body>
</html>
Here is the list of changes that demonstrates how to notify a controller once the map is created.
For directive:
$scope.$emit('onCreate',map);
For controller:
$scope.$on('onCreate', function (event, map) {
$scope.map = map;
//the remaining code goes here...
});
Demo on CodePen

How to get the current location from this here map?

Below is the code of a here map. I'd like to know how can I get the current location from the map? Anyone has ideas? Thanks in advance.
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css"
href="https://js.api.here.com/v3/3.0/mapsjs-ui.css" />
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 700px; background: #ccc" />
<script type="text/javascript" charset="UTF-8" >
/**
* Boilerplate map initialization code starts below:
*/
function showMap(position) {
// Show a map centered at (position.coords.latitude, position.coords.longitude).
}
navigator.geolocation.getCurrentPosition(showMap);
//Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useCIT: true,
useHTTPS: true
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Eindhoven
var map = new H.Map(document.getElementById('map'), defaultLayers.normal.map, {center: {lat: 51.4484160, lng: 5.4916750}, zoom: 13}) ;
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
function addCircleToMap(map){
// Color of the dot, later on change this into interactive wheel
var dotcolor = 'green';
map.addObject(new H.map.Circle(
// The central point of the circle
{lat: 51.4484160, lng: 5.4916750},
// The radius of the circle in meters
100,
{
style: {
strokeColor: 'white', // Color of the perimeter
lineWidth: 2,
fillColor: dotcolor // Color of the circle
}
}
));
}
// Now use the map as required...
addCircleToMap(map);
</script>
</body>
</html>
Below is the code of a here map. I'd like to know how can I get the current location from the map? Anyone has ideas? Thanks in advance.
Im not sure when you are using api.here.com. Maybe you can use google.maps.Geocoder like i did below. This will set lat and lng equal to your position, if its turns on in your browser of cause.
libary:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
Js:
var geocoder;
geocoder = new google.maps.Geocoder();
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 codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
alert("Found you! at Latitude: " +lat + " and Longitude: " +lng);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
latlon = new google.maps.LatLng(lat, lon)
mapholder = document.getElementById('mapholder')
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
var marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>

height percentage not working for google map api

I am working on a tracking system for my laptop, I used google map api to view the current location on a map...
The height % stopped working, but only for the map canvas
Why is this?
Here is the code (sorry a little messy, still sort of a noob...)
var pass_entered;
var pass_entered2;
var password="P#sSWORD";
var randomstring = Math.random().toString(36).slice(-5);
X = document.cookie.split("=")[1]
if ( X != "logged on" ) {
while (pass_entered!=password) {
pass_entered=prompt('PASSWORD REQUIRED FOR ACCESS:','');
if (pass_entered!=password){
alert("Warning! incorrect password entered");
}}}
document.cookie = "logon= logged on; path=/";
self.close();
</script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Find your device</title>
<style>
body{
height: 100;
}
.status{
background-color:#00003D;
}
#panel{
background-color:#CC2900;
}
#map-canvas{
background-color:#008F00;
height: 80;
margin: 0px;
padding: 10px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 15,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = "Fortville,Indiana";
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Sorry, It seems something went wrong finding the location of your device error code:' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<br>
<input type="button" value="Refresh location" onclick="codeAddress();">
<button id="lost_on" onclick="window.open( 'lost.php' , '_blank' );">Turn on lost mode</button>
<button id="lost_off" onclick="window.open( 'lost_off.php' , '_blank' );">Turn off lost mode</button>
Please note you need to manually refresh the location!
</div>
<center>
<div id="map-canvas"></div>
<br>
<iframe class="status" src="status.php" height=40 frameborder="0" ><iframe/>
</center>
</body>
<p> Code is modified code from google map api geocoding service</p>
</html>

Angular ui-map (google map) residing in html partial and hidden with ng-if does not add markers

I hide the map-element initially using ng-if. When the ng-if evaluates to true I cannot add markers to the map. The map-element is contained in a html partial - it is not part of the initial html-page.
HTML:
<div ng-controller="MapCtrl">
<div style="width:100%;height:300px" ng-if="whatever">
<div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"
ui-event="{'map-click': 'openMarkerInfo(marker)'}">
</div>
<div id="map_canvas" ui-map="myMap" class="map"
ui-event="{'map-click': 'addMarker($event, $params)', 'map-zoom_changed': 'setZoomMessage(myMap.getZoom())' }"
ui-options="mapOptions">
</div>
</div>
<div style="width:100%;height:300px;background:yellow" ng-click="showMap()">
</div>
</div>
JS:
angular.module('doc.ui-map', ['ui.map','ngRoute'])
.controller('MapCtrl', ['$scope','$timeout', function ($scope,$timeout) {
$scope.myMarkers = [];
$scope.mapOptions = {
center: new google.maps.LatLng(35.784, -78.670),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.addMarker = function ($event, $params) {
console.log('addMarker');
$scope.myMarkers.push(new google.maps.Marker({
map: $scope.myMap,
position: $params[0].latLng
}));
};
$scope.setZoomMessage = function (zoom) {
$scope.zoomMessage = 'You just zoomed to ' + zoom + '!';
console.log(zoom, 'zoomed');
};
$scope.openMarkerInfo = function (marker) {
$scope.currentMarker = marker;
$scope.currentMarkerLat = marker.getPosition().lat();
$scope.currentMarkerLng = marker.getPosition().lng();
$scope.myInfoWindow.open($scope.myMap, marker);
};
$scope.showMap = function(){
$scope.whatever = true;
}
$scope.setMarkerPosition = function (marker, lat, lng) {
marker.setPosition(new google.maps.LatLng(lat, lng));
};
}]) ;
The 'ng-if' directive will create or remove a portion of DOM based on expression. The ng-if expression is equal to false when you launch the map app.
So the map-ui element does't append to DOM tree and the 'myMap' property won't be added to the controller scope. This will make addMarker() broken because $scope.myMap === undefined
You could try to add the following code to your addMarker function and it should show undefined on your console:
console.log($scope.myMap);
Although ng-show caused the wrong map width/height problem, you could enforce map refresh by dispatching "resize" event when initialize the map.
You need to trigger a event "resize" on Google map object when you want to refresh the map.
google.maps.event.trigger(map,"resize");
My Example:
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular UI Map</title>
</head>
<body>
<div id="map" ng-controller="mapCtrl">
<input type="button" ng-click="showMap()"/>
<div ng-show="isShow">
<div id="map_canvas" ui-map="myMap" style="height:200px;width:300px" ui-event="{'map-click':'addMarker($event, $params)'}" ui-options="mapOptions">
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="js/angular-ui-utils/modules/event/event.js"></script>
<script src="js/angular-ui-map/src/map.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=onGoogleReady"></script>
<script src="js/angularUIMap.js"></script>
<script>
function onGoogleReady(){
angular.bootstrap(document.getElementById("map"),['mapApp']);
}
</script>
</body>
</html>
angularUIMap.js
angular.module("mapApp",['ui.map'])
.controller("mapCtrl",function($scope,$timeout){
var mapInitFlag = false;
$scope.showMap = function(){
$scope.isShow = !$scope.isShow;
if(!mapInitFlag)
{
$timeout(function(){
google.maps.event.trigger($scope.myMap,'resize');
mapInitFlag=true;
console.log('adjust map');
});
}
};
$scope.myMarkers = [];
$scope.mapOptions = {
center: new google.maps.LatLng(35.784, -78.670),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.addMarker = function ($event, $params){
$scope.myMarkers.push(new google.maps.Marker({
map: $scope.myMap,
position: $params[0].latLng
}));
};
});
Screenshot:
Hope this helpful.

Drop Down Menu (Sidebar)

I've put together the code below to load marker data from my SQL database which correctly shows all of the information held.
I'd like to now include a drop down menu that shows the markers by their 'Location Name' and when the user selects the location the associated marker bounces. I know from some of the information that I've found that this is a sidebar? Could someone perhaps please point me in the right direction as to how I would go about adapting my code to include this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>All Locations</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:6,
mapTypeId: 'roadmap'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("locationname");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("osgb36lat")),
parseFloat(markers[i].getAttribute("osgb36lon")));
var marker = new google.maps.Marker({
map: map,
position: point,
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onLoad="load()">
<div id="map"
</div>
</body>
</html>
UPDATE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map My Finds - All Locations</title>
<link rel="stylesheet" href="css/alllocationsstyle.css" type="text/css" media="all" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
Location Name
<script type="text/javascript">
var customIcons = {
0: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
1: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:6,
mapTypeId: 'roadmap'
});
// Change this depending on the name of your PHP file
downloadUrl("mapmyfindsloadalllocations.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var locationname = markers[i].getAttribute("locationname");
var address = markers[i].getAttribute("address");
var finds = markers[i].getAttribute("finds");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("osgb36lat")),
parseFloat(markers[i].getAttribute("osgb36lon")));
var icon = customIcons[finds] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: locationname + ' - ' + address,
icon: icon.icon,
shadow: icon.shadow
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script type="text/javascript">
function animate(element) {
var marker = getMarkerByName(element.title);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() { marker.setAnimation(null); }, 200); }
function getMarkerByName(name) {
// retrieve and return the marker from where you stored it }
</script>
</head>
<body onLoad="load()">
<div id="map"></div>
<label></label>
</body>
</html>
Here's an idea:
Associate each location name with the link in the drop down menu.
Store the marker for each location.
When you click a link from the drop down menu, retrieve the marker associated with that location and simply call a function that animates it:
....
<!-- assuming this is an item from the menu -->
Location Name
....
The script:
<script type="text/javascript">
function animate(element) {
var marker = getMarkerByName(element.title);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() { marker.setAnimation(null); }, 200);
}
function getMarkerByName(name) {
// retrieve and return the marker from where you stored it
}
</script>
...
Something like that
UPDATE:
There is basically no change... when you click the link, highlight it and call the animate function.
For highlighting the correct link on marker click, "listen" for click on each marker:
google.maps.event.addListener(marker, 'click', function(event) {
// animate marker
// highlight the link associated with the marker.
});