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&</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
Related
I am learning the Google Maps API and I am trying to move an object on the map. I created a test page which shows a marker on start, but after calling a function which increases the longitude it removes the marker from the map. There is no error in the console. Can someone look at my code and help me figure out why this is happening?
Javascript file:
var app = angular.module('angularGoogleMapsTestApp', ['uiGmapgoogle-maps']);
var increment = 2.02;
var startingLongitude = -122.44;
var startingLatitude = 37.769;
app.controller('angularGoogleMapCtrl', function ($scope, $log, $rootScope) {
$scope.map = {center: {latitude: 37.7699298, longitude: -122.4469157}, zoom: 12};
$scope.markers = [];
$scope.removeMarkers = function () {
$scope.markers = [];
}
function init() {
$scope.markers.push(
{
id: 0,
latitude: startingLatitude,
longitude: startingLongitude
});
$log.info(JSON.stringify($scope.markers));
}
$scope.moveMarker = function () {
var old = $scope.markers[0].longitude;
$scope.markers.splice(0, 1);
$scope.markers.push(
{
id: 0,
latitude: startingLatitude,
longitude: (old + increment)
});
$log.info(JSON.stringify($scope.markers));
};
init();
});
and html:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>ngMap Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="bower_components/angularjs/angular.js"></script>
<script src="bower_components/lodash/dist/lodash.js"></script>
<script src='bower_components/angular-google-maps/dist/angular- google-maps.js'></script>
<script src="angularGoogleMapsTestApp.js"></script>
<style>
.angular-google-map-container { height: 400px; }
</style>
</head>
<body ng-app="angularGoogleMapsTestApp">
<h3>Angular Google Maps Test</h3>
<p>Test showing adding and removing markers on Angular Google Maps
(from: <a href="http://angular-ui.github.io/angular-google-maps/#!/">
Angular Google Maps</a>)</p>
<div ng-controller="angularGoogleMapCtrl">
<input ng-click="moveMarker()" type="button" value="moveMarker">
<input ng-click="removeMarkers()" type="button" value="Remove markers">
<div style="height:500px">
<ui-gmap-google-map center='map.center' zoom='map.zoom'>
<ui-gmap-markers models="markers" coords="'self'" modelsbyref="false"/>
</ui-gmap-google-map>
</div>
</div>
</body>
</html>
If you are using Angular Google maps v1.2.0 or higher, your marker objects require an idKey, described here in the docs. You can change your current id key with idKey like so:
$scope.markers.push({
idKey: 0,
latitude: startingLatitude,
longitude: startingLongitude
});
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
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.
I`m trying to Update markers position every X time and wonder what is the best way to do that and if there is good example for it.
my code is:
<?php
include 'connect.php';
$json= array();
$res = "SELECT LatLon,fname FROM customers";
$res = mysql_query($res);
while($r = mysql_fetch_assoc($res)) {
$XY = explode(",",$r['LatLon']);
$json[]= array($r['fname'],$XY[1],$XY[0]);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var map;
// Cretes the map
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// This function takes an array argument containing a list of marker data
function generateMarkers(locations) {
for (var i = 0; i < locations.length; i++) {
new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
title: locations[i][0]
});
}
}
</script>
</head>
<body>
<div id="map" style="width: 1000px; height: 700px;"></div>
<script type="text/javascript">
window.onload = function () {
initialize();
var locations = <?php echo json_encode($json); ?>;
//setInterval(function(){generateMarkers(locations);},1000);
generateMarkers(locations);
};
</script>
</body>
</html>
I need to put the data in other file? if yes how to do that? and how I can make the refresh only on the markers and not on the page.
any suggestions?
thanks!
Using JQuery $.ajax();
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var map;
// Cretes the map
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// This function takes an array argument containing a list of marker data
function generateMarkers(locations) {
for (var i = 0; i < locations.length; i++) {
new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
title: locations[i][0]
});
}
}
</script>
</head>
<body>
<div id="map" style="width: 1000px; height: 700px;"></div>
<script type="text/javascript">
window.onload = function () {
initialize();
setInterval(function()
{
$.ajax({
url: "http://yoursite.com/location.php",
type: "POST",
data: {func: 'getLocation'},
success: function(data) {
generateMarkers(data);
}
});
}, 1000);
};
</script>
</body>
</html>
location.php:
<?php
include 'connect.php';
if (isset($_POST['func']) && $_POST['func'] === 'getLocation')
{
echo getLocation();
function getLocation()
{
$json= array();
$res = "SELECT LatLon,fname FROM customers";
$res = mysql_query($res);
while($r = mysql_fetch_assoc($res)) {
$XY = explode(",",$r['LatLon']);
$json[]= array($r['fname'],$XY[1],$XY[0]);
}
return $json;
}
}
?>
Try it!
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.
});