I must adjust a website, but I don't understand this function:
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow;
var appena_entrato = true;
var mappa_attiva = "tt";
-- Initialize_map
function initialize_map() {
markersArray = [];
var myLatlng = new google.maps.LatLng(45.6841895,11.4775636);
var myOptions = {
zoom: 14,
maxZoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: false,
streetViewControl: false
}
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas-"+mappa_attiva), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(45.6841895,11.4775636),
map: map,
title:"COMPANY NAME"
});
marker.setMap(map);
var contentString = '<div>'+
'<h2>COMPANY NAME</h2>'+
'<div style="width:400px;">'+
'<p>ADDRESS<br>' +
'Ph. +39 0000- Fax. +39 00000</p>'+
'</div>'+
'</div>';
marker.infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
marker.infowindow.open(map,marker);
});
markersArray.push(marker);
for (i in markersArray) {
markersArray[i].infowindow.open(map,markersArray[i]);
}
getLocation();
}
-- GetLocation
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
//console.log("Geolocation not supported!");
}
}
-- ShowPosition
function showPosition(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatlng);
map.setZoom(9);
coordsAddress(position.coords.latitude,position.coords.longitude,function(results){
for (var i=0; i<results.length; i++) {
for (var b=0; b<results[i].types.length; b++) {
if (results[i].types[b] == "administrative_area_level_2") {
var indice = i;
}
}
}
for (var i=0; i<results[indice].address_components.length; i++) {
for (var b=0; b<results[indice].address_components[i].types.length; b++) {
if (results[indice].address_components[i].types[b] == "administrative_area_level_2") {
var postalCode = results[indice].address_components[i].short_name;
}
}
}
$("#provincia option:selected").removeAttr("selected");
$("#provincia option[value="+postalCode+"]").prop("selected",true);
mostra_coords(position.coords.latitude, position.coords.longitude, 50);
});
}
-- Code Address
function codeAddress(zipCode,country,callback) {
geocoder.geocode({address: zipCode, region: country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
-- CoordsAddress
function coordsAddress(latitude,longitude,callback) {
var myLatlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({'latLng': myLatlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
--Add marker
function add_spillo(indirizzo) {
var id = indirizzo.attr("id");
var geo = indirizzo.attr("rel");
var text = indirizzo.parent().html();
var icona = 'img/point.png';
indirizzo = geo.split(",");
var myLatlng = new google.maps.LatLng(indirizzo[0],indirizzo[1]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: icona
});
marker.infowindow = new google.maps.InfoWindow({
content: text
});
google.maps.event.addListener(marker, 'click', function () {
marker.infowindow.open(map, marker);
});
markersArray.push(marker);
bounds.extend(myLatlng);
}
-- Map centre
function centra_mappa(coords) {
var lat = coords.lat();
var lon = coords.lng();
var max_lon = map.getBounds().getNorthEast().lng();
var max_lat = map.getBounds().getNorthEast().lat();
var min_lon = map.getBounds().getSouthWest().lng();
var min_lat = map.getBounds().getSouthWest().lat();
max_lon = Math.max(lon, max_lon);
min_lon = Math.min(lon, min_lon);
max_lat = Math.max(lat, max_lat);
min_lat = Math.min(lat, min_lat);
var ne = new google.maps.LatLng(max_lat, max_lon);
var sw = new google.maps.LatLng(min_lat, min_lon);
var nuovi_bordi = new google.maps.LatLngBounds(sw, ne);
map.fitBounds(nuovi_bordi);
}
-- Delete Overlays
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].infowindow.close();
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
-- Coords Show
function mostra_coords(lat, lng, distance) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
lat: lat,
lng: lng,
distance: distance,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search1");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
appena_entrato = false;
});
}
-- Provincia Show
function mostra(provincia) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
provincia: provincia,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search2");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
--Nazione Show
function mostra_nazione(nazione) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
country: nazione,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search3");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize_map);
$(document).ready(function(){
$("#provincia-ttt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#provincia-tt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#nazione-ttt").change(function(){
console.log($(this).val());
if ($(this).val() == "IT") $("#teen_provincia").show();
else {
$("#teen_provincia").hide();
mostra_nazione($(this).val());
}
});
$('#tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
if ($(this).attr('href') == "#orange") {
mappa_attiva = "ttt";
} else {
mappa_attiva = "tt";
}
initialize_map();
$("#provincia-"+mappa_attiva).val("");
$("#boxNegozi-"+mappa_attiva+" ul").html("");
});
});
-- I MADE THIS PHP PAGE BUT DON'T WORK, WHERE I MAKE ERROR? thanks in advance
<?
$dbname ='ltaketwd_db'; //Name of the database
$dbuser ='ltaketwd_admin'; //Username for the db
$dbpass ='Twork.01'; //Password for the db
$dbserver ='localhost'; //Name of the mysql server
$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$query = mysql_query("SELECT * FROM negozi");
while ($row = mysql_fetch_array($query)){
$lat=$row['lat'];
$lng=$row['lng'];
$distance=$row['distance'];
$name=$row['name'];
$indirizzo=$row['indirizzo'];
$provincia=$row['provincia'];
$nazione=$row['nazione'];
}
?>
AJAX = Asynchronous JavaScript and XML.
In short; AJAX allows you to load data in the background, manipulate it and display it on the webpage, without needing a page reload.
Have a look at jQuery's documentation for load().
You'll see that load() takes up to three parameters, which is what happens here :
$("#boxStore-"+active_map+" ul") // the element you want as container for your document
.load(
customurl, // 1) the page/document you want to load in the container
{lat:lat, ..... }, // 2) variables you pass to the page so it generates differently
function(data) {
/* 3) callback function, that will be executed after load() is finished. "data" is the page/document you called. */
}
);
Related
In my Laravel Application i use google map to Display Route and Distance Between Two Places. after setting google map, i test my app. its display as Blank Screen. I even registered the application using a key that I applied for on Google's website. I have been working on this for 2 hours and cannot figure it out.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY API KEY&libraries=places&callback=initMap&sensor=false" async defer></script>
<script type="text/javascript">
function GetRoute() {
source = document.getElementById("pickupaddress").value;
destination = document.getElementById("deliveryaddress").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var dvDistance = document.getElementById("distanceops");
dvDistance.innerHTML = "";
dvDistance.innerHTML += distance;
} else {
alert("Unable to find the distance via road.");
}
});
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 4.2105, lng: 101.9758},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('pickupaddress');
var destinationInput = document.getElementById('deliveryaddress');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var deliveryrestrictOptions = {componentRestrictions: {country: 'my'},placeIdOnly: true};
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, deliveryrestrictOptions);
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput,deliveryrestrictOptions);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
GetRoute();
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
window.ParsleyConfig = {
errorsWrapper: '<div></div>',
errorTemplate: '<span class="error-text"></span>',
classHandler: function (el) {
return el.$element.closest('input');
},
successClass: 'valid',
errorClass: 'invalid'
};
</script>
I have worked on google maps. Google maps won't load inside a modal or any hidden divs (for perf reasons).
Here is what you do. Trigger resize on the map and it should render the map.
google.maps.event.trigger(map, 'resize') where map is your map instance name.
I'm trying to place multiple markers on a map. For this, I followed this procedure
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete?csw=1
Demo
But here, once user starts typing for another marker, then first marker is getting replaced by the second marker. For this, I initialized the marker inside autocomplete function so that it creates another marker as user enters second one. This worked fine. Another marker is getting pinned. But onclicking the marker, it will not produce infowindow since the infowindow is inside autocomplete function.
I need infowindow for all markers.
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var marker = new google.maps.Marker({
map: map
});
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(17); // Why 17? Because it looks good.
}
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(' ');
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35),
}));
if (address.length != 0) {
address = place.name + ', ' + address;
} else {
address = place.name;
}
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here infowindow will not work since there is no action listener for this. so I wrote the below code.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
But it wont work as marker is out of scope variable here. How to do this? Please help
Use a createMarker function to hold function closure on the infowindow content.
<script type="text/javascript">
var map = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
// 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(17); // Why 17? Because it looks good.
}
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(' ');
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35),
}));
if (address.length != 0) {
address = place.name + ', ' + address;
} else {
address = place.name;
}
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
createMarker(place);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
working example
I can display all the markers from a request, but they point with a little gap in my map.
For instance, New York is pointed near Quebec. If I zoom into the map, all the markers move close to the right position.
Does anyone know how to fix it?
My code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.1&sensor=true"></script>
<script type="text/javascript">
//<![CDATA[
var geocoder;
var map;
var timeout = 600;
var address_position = 0;
var address = [
<?php
$_list="";
$_unicite=array();
foreach($search_data as $k => $item)
{
$_address=trim($item->meta_value);
if(!empty($_address))
{
if(!in_array($_address,$_unicite)){
$_unicite[$item->post_id]=$_address;
$_list.='"'.$_address.'",';
}
}
}
if(!empty($_list)) {
$_list=substr($_list,0,abs(strlen($_list)-1));
}
echo $_list;
?>
];
var link = [
<?php
$_list2="";
$_unicite2=array();
foreach($search_data as $k => $item)
{
$_link=trim($item->post_id);
if(!empty($_link))
{
if(!in_array($_link,$_unicite2)){
$_unicite2[$item->post_id]=$_link;
$_list2.='"'.$_link.'",';
}
}
}
if(!empty($_list2)) {
$_list2=substr($_list2,0,abs(strlen($_list2)-1));
}
echo $_list2;
?>
];
var title = [
<?php
$_list3="";
$_unicite3=array();
foreach($search_data as $k => $item)
{
$_title=trim($item->post_title);
if(!empty($_title))
{
if(!in_array($_title,$_unicite2)){
$_unicite2[$item->post_id]=$_title;
$_list3.='"'.$_title.'",';
}
}
}
if(!empty($_list3)) {
$_list3=substr($_list3,0,abs(strlen($_list3)-1));
}
echo $_list3;
?>
];
var image = new google.maps.MarkerImage(
'http://www.bookyourparis.com/images-site/beachflag.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function addMarker(position)
{
geocoder.geocode({'address': address[position]}, function(results, status)
{
address_position++;
if (address_position < address.length)
{
setTimeout(function() { addMarker(address_position); }, (timeout));
}
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
{
setTimeout(function() { addMarker(position); }, (timeout * 3));
}
/**
if (address_position < address.length)
{
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
{
setTimeout(function() { addMarker(position); }, (timeout * 3));
} else {
setTimeout(function() { addMarker(address_position); }, (timeout));
}
}
/**/
else if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address[position],
icon: image,
});
var contentString = '<div id="content_bulle"><div id="bodyContent_bulle" style="margin-top:5px;">'+
'<h1 style="font-size:1.5em">'+title[position]+
'</h1><h2 style="font-size:1.2em">'+results[0].formatted_address+
'</h2><p style="color:#AF1A40"><a target="_blank" href="?p='+link[position]+'">View</a></p>'+
'</div></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxHeight: 100
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
});
}
function codeaddress() {
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.HYBRID,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker(address_position);
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
jQuery(window).load( function(){
codeaddress();
});
//]]>
</script>
<div id="map_canvas" style="width: 940px; height: 420px;border:1px solid #999"></div>
I'm trying to display an array of postcodes onto a google map using PHP and using the Symfony Framework (1.0)
The main problem I am having, is that there is some text associated with each marker, i.e when you click the marker a popup appears.
The main problem is that the text should point to the correct postcode/marker on the map, but for some reason this doesn't seem to be the case:
<?php
$addresses = array();
foreach($contents->getResults() as $content):
$addresses[] = array(
'postcode'=>sprintf('%s',str_replace(' ','',$content->getPostalCode())),
'html'=>escape_javascript(get_partial('property/propertyList',array('content'=>$content))),
);
endforeach;
?>
<?php
echo javascript_tag("
var map;
var localSearch = new GlocalSearch();
var center = false;
var icon = new GIcon();
icon.image = 'http://www.google.com/mapfiles/marker.png';
icon.shadow = 'http://www.google.com/mapfiles/shadow50.png';
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);
var delay = 100;
var bounds = new GLatLngBounds();
var addresses = ".json_encode($addresses).";
var nextAddress = 0;
function theNext() {
if (nextAddress < addresses.length) {
var postcode = addresses[nextAddress].postcode;;
var html = addresses[nextAddress].html
setTimeout('getAddress(\"'+postcode+'\",\"'+html+'\",theNext)', delay);
nextAddress++;
}
}
function getAddress(search, html, next) {
usePointFromPostcode(search, html);
next();
}
var geoCount = 0;
function usePointFromPostcode(address, html, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
geoCount++;
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
var marker = new GMarker(point);
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
map.addOverlay(marker);
bounds.extend(point);
if(geoCount == addresses.length) {
setCenterToBounds();
}
}else{
//console.info('Postcode not found!', address);
}
});
localSearch.execute(address + ', UK');
}
function placeMarkerAtPoint(point, html)
{
var marker = new GMarker(point,icon);
map.addOverlay(marker);
}
function setCenterToBounds()
{
map.setCenter(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds));
console.info('zoom',map.getBoundsZoomLevel(bounds));
}
function mapLoad() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById('map'));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
theNext();
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function addUnLoadEvent(func) {
var oldonunload = window.onunload;
if (typeof window.onunload != 'function') {
window.onunload = func;
} else {
window.onunload = function() {
oldonunload();
func();
}
}
}
addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
")
?>
It only happens on some of the markers though. It is like it finds the postcode, puts the marker on, but then displays the wrong details for it
Ok, so it seems that the data coming back from Google, seemed to come back in the wrong order.
Changing the var delay = 100 to var delay = 200 seemed to fix this
Even though it made the map load a little bit slower
I am trying to pass dynamic data from mysql then creating multiple markers on google.
Here is my html code.
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div class="map">
<div id="map" style="width: 100%;height:738px;"></div>
</div>
</div>
Here is the angularjs Script.
//Angular App Module and Controller
var investup = angular.module('mapsApp', [])
investup.controller('MapCtrl', function ($scope, $compile) {
var cities = [
{
title: 'xyz',
city : '<img src="images/xxx.jpg" />',
lat : 12.2917925,
long : 76.6704174
},
{
title: 'Add to Cart',
city : '<button class="org-btn" ng-click="cartone()" style="display:block;font-size:12px;margin:0 auto 0 auto;">Add to Cart</button>',
lat : 12.2725645,
long : 76.6705986
},
];
//Define your locations: HTML content for the info window, latitude, longitude
var popup = [
['<img src="images/xyz.jpg" />'],
['<img src="images/xyz.jpg"/>'],
];
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [iconURLPrefix + 'red-dot.png', iconURLPrefix + 'purple-dot.png']
var iconsLength = icons.length;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(12.2982778, 76.6903664),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
}
$scope.popup = popup;
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var activeInfoWindow;
var activeInfoWindow2;
var iconCounter = 0;
$scope.markers = [];
for (i = 0; i < cities.length; i++) {
var createMarker = function (info) {
var marker = new google.maps.Marker({map: $scope.map,icon: icons[iconCounter],position: new google.maps.LatLng(info.lat, info.long),popup: popup[i][0]});
google.maps.event.addListener(marker, 'click', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
var contentString = "<div><h2>" + info.city + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow = infoWindow;
});
google.maps.event.addListener(marker, 'mouseover', function() {
var contentString = "<div><h2>" + marker.popup + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow2 = infoWindow;
if(activeInfoWindow != null)
activeInfoWindow.close();
});
google.maps.event.addListener(marker, 'mouseout', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
});
$scope.markers.push(marker);
}
createMarker(cities[i]);
iconCounter++;
}
$scope.openInfoWindow = function(e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Here is the screenshot of the result
This is the static code when i'm placing php code in cities and popup section to not showing the result.
Problem is when i don't how to call php code in angularJS. Kindly help me.
Thanks in advance.
1- You probably would need to use a framework to handle JSON serialization for you.
For the sake of simplicity you can use this library (https://github.com/mevdschee/php-crud-api), and copy api.php to the server root directory.
2- Using $http:
investup.controller('MapCtrl', function($scope, $compile, $http) {
$http.get('/api.php/cities').success(function(response) {
var cities = response.cities;
// the rest of controller function body
}).catch(handleError);
})