Google Maps SetCenter. Focus on new location - javascript

I'm using google maps and rendering many markers at http://www.dentalo.se/search/stockholm and it is working fine.
What I would like to do is when someone clicks on a button I want to use map.SetCenter and focus on that location.
I have a Information button
when a user clicks on it I am calling a JavaScript function and setting the center. But is not working. When I click on information it just becomes gray. You can try it yourself and see what happpenes at http://www.dentalo.se/search/stockholm.
function showCompany(latlong) {
map.setCenter(latlong);
alert(latlong);
}
This is the jquery code for rendering the map
var p = $("#map_search");
var position = p.position();
$("#directionsPanel").css({top: position.top, position:'absolute'});
var map;
var addressField;
var geocoder;
$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ShowPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
function ShowPosition(position) {
//begin rest call
$("#latitude").val(position.coords.latitude);
$("#longitude").val(position.coords.longitude);
var from = $("#latitude").val() + "," + $("#longitude").val();
var urlParts = window.location.href.split('/'),
Id = urlParts[(urlParts.length - 1)];
$.ajax({
type: "GET",
cache: true,
async: false,
url: "/RestService/Dentalo.svc/CompaniesByState/" + Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
map = new GMaps({
el: 'map_search',
//center: Id,
lat: data[0].State.Latitude ,//position.coords.latitude,
lng: data[0].State.Longitude,
zoom: 14,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DEFAULT,
position: google.maps.ControlPosition.RIGHT_RIGHT
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
scrollwheel: true
});
map.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
title: 'Min position',
icon: 'http://www.dentalo.se/assets/img/map/user_x64.png'
});
var h = "";
$.each(data, function (index, item) {
var to = item.Latitude + "," + item.Longitude;
h += "<div class='row buttons-page'>" +
"<div class='col-md-8 col-sm-4'>" +
"<h4>"+ item.Name + "</h4>" +
"<p style='margin: 1px;'>" + item.Address + ", " + item.County.Name + "</p>" +
"<p style='margin: 1px;'>" + item.Phone + "</p>" +
"<p style='margin: 1px;'>Distans: " + calcRoute(from, to) + "</p>" +
"</div>" +
"<div class='col-md-3 col-sm-9'>" +
"<div class='btn-group'>" +
"<a href='/booking/"+ item.CompanyId +"' class='btn " + bookable(item.Status) + " " + SetDisplayClass(item.Status) +"'>Boka <i class='m-icon-swapright m-icon-white'></i></a>" +
"<button type='button' class='btn default' onClick='showCompany(&apos;" + to + "&apos;);return false;'>Information <i class='icon-info-sign m-icon-white'></i></button>" +
"</div>" +
"</div>" +
"</div>" +
"<hr style='margin: 1px;' />";
map.addMarker({
lat: item.Latitude ,
lng: item.Longitude ,
title: item.Address ,
icon: GetMarkerImage(item.Status),
infoWindow: {
content: '<div style="width: 300px"><h4>' + item.Name + '</h4><br /><p>' + item.Address + ', ' + item.County.Name + '</p><div class="four columns alpha"><a class="btn blue ' + SetDisplayClass(item.Status) + '" href="/booking/' + item.CompanyId + '" ><i class="m-icon-swapright m-icon-white"></i> Boka</a> Information</div></div>',
}
})
});
$("#search_panel").html(h).show();
},
error: function (msg, url, line) {
//alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
//end rest call
// Define Gecoder
geocoder = new google.maps.Geocoder();
// Init searchbox
initSearchBox();
// main directions
}
How can I set SetCenter when a user clicks on the "Information" button?
Thanks in advance.

map.setCenter(latlong);
latlong must be a google.maps.LatLng object but in your case you are passing a string to your function.
<button onclick="showCompany('59.3618356,18.0140273');return false;">Information</button>
So that won't work.
Instead try:
<button onclick="showCompany('59.3618356','18.0140273');return false;">Information</button>
And
function showCompany(lat, lng) {
var position = new google.maps.LatLng(lat, lng);
map.setCenter(position);
alert(lat, lng);
}

Related

Mapbox Javascript API function event call order

I am only attaching the script tag. Below is the flow of events that happen and the problem I see. I would appreciate any suggestions/advice.
I trigger the businessGeocoder by searching for an address, which triggers the businessAddress function inside the initialize function, which in turn triggers the businessLocationClickInfo function. This works perfectly.
Without refreshing the page I decide to use the employeeResidenceGeocoder by searching for an address, which triggers the employeeResidenceAddress function inside the initialize function, which in turn triggers the employeeResidenceLocationClickInfo function. This works perfectly. too.
Again, without refreshing the page I decide to use the businessGeocoder again by searching for an address, which triggers the businessAddress function inside the initialize function, which in turn SHOULD trigger the businessLocationClickInfo function, but instead, it triggers the employeeResidenceLocationClickInfo function. The employeeResidenceLocationClickInfo function, while it should have not been called, returns the correct data. I am having a hard time understanding why it is being called instead of the businessLocationClickInfo function.
Please note that doing it the other way, using employeeResidenceGeocoder first and then businessGeocoder, and then back to employeeResidenceGeocoder causes the same problem.
Update>> I ran console logs after each line and found out that because the click events are called in the initialize function, every time I click on the map both businessLocationClickInfo and employeeResidenceLocationClickInfo are being called, one replacing the other output div, whereas I want to only call one of them, depending on the geocoder. But I still haven't found a way/order to fix it.
<script>
var map;
var businessGeocoder;
var employeeResidenceGeocoder;
var businessLocationClickFeature;
var employeeResidenceLocationClickFeature;
var screenPoint;
var address;
var geocodeFeature;
var geocodePopup;
var geocodeCensusTract;
var geocodeCensusBlockGroup;
var businessLocationPolygon;
var employeeResidenceLocationPolygon;
function initialize() {
businessGeocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
flyTo: {
speed: 100
},
zoom: 17,
placeholder: "Search for a business location",
mapboxgl: mapboxgl
})
employeeResidenceGeocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
flyTo: {
speed: 100
},
zoom: 17,
placeholder: "Search for an employee's residence",
mapboxgl: mapboxgl
})
// // // adds geocoder outside of map (inside of map would make it a 'map control')
// document.getElementById('geocoder1').appendChild(businessGeocoder.onAdd(map));
// document.getElementById('geocoder2').appendChild(employeeResidenceGeocoder.onAdd(map));
map.addControl(businessGeocoder);
map.addControl(employeeResidenceGeocoder);
businessGeocoder.on('result', businessAddress);
employeeResidenceGeocoder.on('result', employeeResidenceAddress);
}
function businessAddress (obj) {
address = obj.result.place_name;
$(".geocode-result-area").html('<b>Geocoded Business Address: </b>' + address + '<br/><div class="medium-font">Click the blue address pin on the map for updated results.</div>');
$(".geocode-click-result-area").html("");
map.on('click', businessLocationClickInfo);
}
function employeeResidenceAddress (obj) {
address = obj.result.place_name;
$(".geocode-result-area").html('<b>Geocoded Employee Residence Address: </b>' + address + '<br/><div class="medium-font">Click the blue address pin on the map for updated results.</div>');
$(".geocode-click-result-area").html("");
map.on('click', employeeResidenceLocationClickInfo);
}
function businessLocationClickInfo (obj) {
businessLocationClickFeature = map.queryRenderedFeatures(obj.point, {
layers: ['tract-4332-1sbuyl','blockgroups-4332-9mehvk','businesslocation']
});
if (businessLocationClickFeature.length == 3) {
$(".geocode-click-result-area").html('<br/>This area meets the <span style="background-color:yellow">business location criteria</span> based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>' + businessLocationClickFeature[2].properties.Inquiry1 + '</td></tr>'
+ '<tr><td>CT & BG Poverty Rate ≥ 20%</td><td>' + businessLocationClickFeature[2].properties.Inquiry2 + '</td></tr></table>'
+ '<p><b>' + businessLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ businessLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ businessLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+'<table><tr><th></th><th>Poverty Rate</th></tr><tr><td>CT '
+ businessLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ businessLocationClickFeature[0].properties.PovRate + "%" + '</td></tr><tr><td>BG '
+ businessLocationClickFeature[1].properties.BLKGRPCE + '</td><td>'
+ businessLocationClickFeature[1].properties.PovRate + "%" + '</td></tr></table>'
);
}
else {
$(".geocode-click-result-area").html('<br/> This area <u style = "color:red;">does not</u> meet the business location criteria based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>No</td></tr>'
+ '<tr><td>CT & BG Poverty Rate ≥ 20%</td><td>No</td></tr></table>'
+ '<p><b>' + businessLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ businessLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ businessLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+ '<table><tr><th></th><th>Poverty Rate</th></tr><tr><td>CT '
+ businessLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ businessLocationClickFeature[0].properties.PovRate + "%" + '</td></tr><tr><td>BG '
+ businessLocationClickFeature[1].properties.BLKGRPCE + '</td><td>'
+ businessLocationClickFeature[1].properties.PovRate + "%" + '</td></tr></table>'
);
}
}
function employeeResidenceLocationClickInfo (obj) {
employeeResidenceLocationClickFeature = map.queryRenderedFeatures(obj.point, {
layers: ['tract-4332-1sbuyl','blockgroups-4332-9mehvk','employeeresidencelocation']
});
if (employeeResidenceLocationClickFeature.length == 3) {
$(".geocode-click-result-area").html('<br/>This area meets the <span style="background-color:yellow">employee residence location criteria</span> based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>' + employeeResidenceLocationClickFeature[2].properties.Inquiry1 + '</td></tr>'
+ '<tr><td>CT % LMI ≥ 70%</td><td>' + employeeResidenceLocationClickFeature[2].properties.Inquiry2 + '</td></tr>'
+ '<tr><td>CT & all BG Poverty Rate ≥ 20%</td><td>' + employeeResidenceLocationClickFeature[2].properties.Inquiry3 + '</td></tr></table>'
+ '<p><b>' + employeeResidenceLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ employeeResidenceLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ employeeResidenceLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+ '<table id="CensusTable"><tr><th></th><th>Poverty Rate</th><th>LMI</th></tr><tr><td>CT '
+ employeeResidenceLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.PovRate + "%" + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.LMIPerc + "%" + '</td></tr>');
var BGsin20PovertyCT = map.queryRenderedFeatures(
{ layers: ['blockgroups-4332-9mehvk'],
filter: ["==", "TRACTCE", employeeResidenceLocationClickFeature[0].properties.TRACTCE]
});
var unique = [];
var distinct = [];
for (let i = 0; i < BGsin20PovertyCT.length; i++ ){
if (!unique[BGsin20PovertyCT[i].properties.BLKGRPCE]){
distinct.push(BGsin20PovertyCT[i]);
unique[BGsin20PovertyCT[i].properties.BLKGRPCE] = 1;
}
}
for (let i = 0; i < distinct.length; i++ ){
$("#CensusTable").append('<tr><td>BG ' + distinct[i].properties.BLKGRPCE + '</td><td>'
+ distinct[i].properties.PovRate + "%" + '</td><td>-</td></tr></table>'
);
}
}
else {
$(".geocode-click-result-area").html('<br/> This area <u style = "color:red;">does not</u> meet the employee residence location criteria based on the following thresholds:'
+ '<table><tr><td>Renewal Community</td><td>No</td></tr>'
+ '<tr><td>CT % LMI ≥ 70%</td><td>No</td></tr>'
+ '<tr><td>CT & all BG Poverty Rate ≥ 20%</td><td>No</td></tr></table>'
+ '<p><b>' + employeeResidenceLocationClickFeature[0].properties.CountyName + " County" + '<br/>'
+ employeeResidenceLocationClickFeature[0].properties.NAMELSAD + '<br/>'
+ employeeResidenceLocationClickFeature[1].properties.NAMELSAD + '</b></p>'
+ '<table id="CensusTable"><tr><th></th><th>Poverty Rate</th><th>LMI</th></tr><tr><td>CT '
+ employeeResidenceLocationClickFeature[0].properties.TRACTCE + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.PovRate + "%" + '</td><td>'
+ employeeResidenceLocationClickFeature[0].properties.LMIPerc + "%" + '</td></tr>');
var BGsin20PovertyCT = map.queryRenderedFeatures(
{ layers: ['blockgroups-4332-9mehvk'],
filter: ["==", "TRACTCE", employeeResidenceLocationClickFeature[0].properties.TRACTCE]
});
var unique = [];
var distinct = [];
for (let i = 0; i < BGsin20PovertyCT.length; i++ ){
if (!unique[BGsin20PovertyCT[i].properties.BLKGRPCE]){
distinct.push(BGsin20PovertyCT[i]);
unique[BGsin20PovertyCT[i].properties.BLKGRPCE] = 1;
}
}
for (let i = 0; i < distinct.length; i++ ){
$("#CensusTable").append('<tr><td>BG ' + distinct[i].properties.BLKGRPCE + '</td><td>'
+ distinct[i].properties.PovRate + "%" + '</td><td>-</td></tr></table>'
);
}
}
}
mapboxgl.accessToken = 'pk.eyJ1Ijoia3l1bmdhaGxpbSIsImEiOiJjanJyejQyeHUyNGwzNGFuMzdzazh1M2k1In0.TcQEe2aebuQZ4G7d827A9Q';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/kyungahlim/ckd226uao1p7i1iqo8ag2ewmu',
center: [-95.925, 29.575],
zoom: 7
});
map.on('load', initialize);
// // Center the map on the coordinates of any clicked symbol from the 'symbols' layer.
// map.on('click', 'symbols', function(e) {
// map.flyTo({
// center: e.features[0].geometry.coordinates
// });
// });
// // Change the cursor to a pointer when the it enters a feature in the 'symbols' layer.
// map.on('mouseenter', 'symbols', function() {
// map.getCanvas().style.cursor = 'pointer';
// });
// // Change it back to a pointer when it leaves.
// map.on('mouseleave', 'symbols', function() {
// map.getCanvas().style.cursor = '';
// });
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-95.925, 29.575]
},
properties: {
title: 'Mapbox',
description: 'Washington, D.C.'
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-122.414, 37.776]
},
properties: {
title: 'Mapbox',
description: 'San Francisco, California'
}
}]
};
// // geocode the typed-in address, zoom to the location, and put a pin on address
// function codeAddress() {
// sAddress = document.getElementById('inputTextAddress').value;
// geocoder.geocode( { 'address': sAddress}, function(results, status) {
// //latitude = results[0].geometry.location.lat();
// //longitude = results[0].geometry.location.lng();
// coordinate = results[0].geometry.location;
// if (status == google.maps.GeocoderStatus.OK) {
// if (GeocodeMarker){
// GeocodeMarker.setMap(null);
// }
// // bounds.extend(results[0].geometry.location);
// // PuppyMap.fitBounds(bounds);
// PuppyMap.setCenter(results[0].geometry.location);
// PuppyMap.setZoom(14);
// GeocodeMarker = new google.maps.Marker({
// map:PuppyMap,
// position: results[0].geometry.location,
// animation: google.maps.Animation.DROP,
// icon: housePin,
// zoom: 0
// });
// }
// else{
// alert("Geocode was not successful for the following reason: " + status);
// }
// });
// }
var marker = new mapboxgl.Marker(document.createElement('div'))
.setLngLat( [-95.925, 29.575])
.addTo(map);
// // add markers to map
// geojson.features.forEach(function(marker) {
// // create a HTML element for each feature
// var el = document.createElement('div');
// el.className = 'marker';
// // make a marker for each feature and add to the map
// new mapboxgl.Marker(el)
// .setLngLat(marker.geometry.coordinates)
// .addTo(map);
// });
</script>

Ionic 2 click event inside infowindow googlemaps

Hi i'm trying to fire an event from a button inside a google maps infowindow.
the problem is that i can´t make it fire by any mean.
addMarket(latitud, longitud, sensorData) {
let marker = new google.maps.Marker({
draggable: false,
position: { lat: latitud, lng: longitud },
map: this.map,//set map created here
title: sensorData.sensor
});
marker.addListener('click', function () {
infowindow.open(this.map, marker);
});
let bodyMessege = 'Nombre del Sensor: ' + sensorData.sensor + '<br>' +
'Componente Descripcion: ' + sensorData.componentDesc + '<br>' +
' description: ' + sensorData.description + '<br>' +
' Tipo de sensor: ' + sensorData.type + '<br>' +
' Unidad de sensor: ' + sensorData.unit + '<br>' +
'Tipo de dato: ' + sensorData.dataType + '<br>' +
' <button ion-button (click)="this.navCtrl.push(DetalleSensorPage)" >Default</button>';
// ' <button ion-button="" onclick=console.log("log");' anda
//this.pushPage=DetalleSensorPage;
var infowindow = new google.maps.InfoWindow({
content: bodyMessege
});
Any tip will be welcome thanks. :)
I have found this solution for my own project: ( https://forum.ionicframework.com/t/ng-click-in-google-maps-infowindow/5537/6)
The key element is the id="tap" that you look for at the getElementbyId below.
let content = '<div class="infowindow"><p id="tap">your text here</p></div>';
let infoWindow = new google.maps.InfoWindow(
{
closeBoxURL: "",
content: content
}
);
infoWindow.open(this.map, marker);
google.maps.event.addListenerOnce(infoWindow, 'domready', () => {
document.getElementById('tap').addEventListener('click', () => {
//alert('Clicked');
console.log("touch");
this.closeInfoViewWindow(infoWindow);
this.openEventDetailModal(event);
});
});
hope this will help you and others.

Google Map Geocoded TypeError in Callback function

I have the following 2 functions to pull in, geocode, and place markers in a google map.
I keep getting a TypeError: adds[i] is undefined, which of course is causing the rest of the map to bomb.
Here is my code:
// Place Markers on the Map
var PlaceMarkers = function (iw, adds, gc) {
var image = {url: "http://meatmysite.com/Images/star2.png", size: new google.maps.Size(24, 24)};
var aCt = adds.length;
for(var i = 0; i < aCt; ++i) {
GetLatLng(gc, adds[i].address, function(pos) {
if(pos) {
var ipop = '<h1>' + adds[i].title + '</h1>'; // <----- TypeError: adds[i] is undefined
if(!isBlank(adds[i].url)){
ipop += '' + adds[i].url + '<br />';
}
ipop += '<div class="map_item_content" id="mi_content' + i + '">' + adds[i].content + '</div>';
if(!isBlank(adds[i].mainphone)){
ipop += '<br /><strong>Phone:</strong> ' + adds[i].mainphone + '';
}
if(!isBlank(adds[i].mainemail)){
ipop += '<br /><strong>Email:</strong> ' + adds[i].mainemail + '';
}
console.log('HEY NOW: ' + pos.toString() + ' - Location Found!');
var mark = new google.maps.Marker({title: adds[i].title, position: pos, map: map, icon: image, html: ipop});
google.maps.event.addListener(mark, 'click', function(){
iw.setContent(this.html);
iw.open(map, this);
});
}
});
}
};
// Get Lat/Lng Location
var GetLatLng = function(gc, add, f) {
var ret = '';
gc.geocode({'address': add}, function(res, status) {
if (status == 'OK') {
f(res[0].geometry.location);
console.log('Found Here: ' + ret.toString());
}
});
return -1;
};
DEMO RETURNED DATA FOR adds
[
{
"address": "1 My Street Gilbert, AZ 85234",
"title": "My Title 1",
"url": "http://www.myurl.com/",
"mainphone": null,
"mainemail": null,
"content": "1 My Street<br />Gilbert, AZ 85234"
},
{
"address": "2 My Street North Richland Hills, TX 76182",
"title": "My Title 2",
"url": null,
"mainphone": null,
"mainemail": null,
"content": "2 My Street<br />North Richland Hills, TX 76182"
}
]
One option, pass the complete "address" object into the GetLatLng function, and from there into its callback (so you get function closure on it):
// Get Lat/Lng Location
var GetLatLng = function (gc, add, f) {
gc.geocode({
'address': add.address
}, function (res, status) {
if (status == 'OK') {
f(res[0].geometry.location, add);
}
});
};
Then use it like this inside the callback (you could pass just the index into the array also):
GetLatLng(gc, adds[i], function (pos, add) {
if (pos) {
var ipop = '<h1>' + add.title + '</h1>';
if (!isBlank(add.url)) {
ipop += '' + add.url + '<br />';
}
ipop += '<div class="map_item_content" id="mi_content' + i + '">' + add.content + '</div>';
if (!isBlank(add.mainphone)) {
ipop += '<br /><strong>Phone:</strong> ' + add.mainphone + '';
}
if (!isBlank(add.mainemail)) {
ipop += '<br /><strong>Email:</strong> ' + add.mainemail + '';
}
console.log('HEY NOW: ' + pos.toString() + ' - Location Found!');
var mark = new google.maps.Marker({
title: add.title,
position: pos,
map: map,
icon: image,
html: ipop
});
google.maps.event.addListener(mark, 'click', function () {
iw.setContent(this.html);
iw.open(map, this);
});
}
});
proof of concept fiddle
code snippet:
var geocoder = new google.maps.Geocoder();
var map;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
PlaceMarkers(infoWindow, adds, geocoder);
}
google.maps.event.addDomListener(window, "load", initialize);
// Place Markers on the Map
var PlaceMarkers = function(iw, adds, gc) {
var bounds = new google.maps.LatLngBounds();
var image = {
url: "http://meatmysite.com/Images/star2.png",
size: new google.maps.Size(24, 24)
};
var aCt = adds.length;
for (var i = 0; i < aCt; ++i) {
GetLatLng(gc, adds[i], function(pos, add) {
if (pos) {
var ipop = '<h1>' + add.title + '</h1>'; // <----- TypeError: adds[i] is undefined
if (!isBlank(add.url)) {
ipop += '' + add.url + '<br />';
}
ipop += '<div class="map_item_content" id="mi_content' + i + '">' + add.content + '</div>';
if (!isBlank(add.mainphone)) {
ipop += '<br /><strong>Phone:</strong> ' + add.mainphone + '';
}
if (!isBlank(add.mainemail)) {
ipop += '<br /><strong>Email:</strong> ' + add.mainemail + '';
}
console.log('HEY NOW: ' + pos.toString() + ' - Location Found!');
var mark = new google.maps.Marker({
title: add.title,
position: pos,
map: map,
// icon: image,
html: ipop
});
bounds.extend(mark.getPosition());
map.fitBounds(bounds);
google.maps.event.addListener(mark, 'click', function() {
iw.setContent(this.html);
iw.open(map, this);
});
}
});
}
};
// Get Lat/Lng Location
var GetLatLng = function(gc, add, f) {
gc.geocode({
'address': add.address
}, function(res, status) {
if (status == 'OK') {
f(res[0].geometry.location, add);
}
});
};
var adds = [{
"address": "1 My Street Gilbert, AZ 85234",
"title": "My Title 1",
"url": "http://www.myurl.com/",
"mainphone": null,
"mainemail": null,
"content": "1 My Street<br />Gilbert, AZ 85234"
}, {
"address": "2 My Street North Richland Hills, TX 76182",
"title": "My Title 2",
"url": null,
"mainphone": null,
"mainemail": null,
"content": "2 My Street<br />North Richland Hills, TX 76182"
}];
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
This looks like a typical binding issue. By the time your callback is called, the value of adds[i] will have changed. It is likely that the loop terminated and i has now a value of last index + 1, which is pointing to nothing. Note that it could also point to the wrong index, that would not fail but use the wrong data.
You must bind the value of adds[i] locally for each iteration or the callback will just use a reference to a global value. There a multiple ways to go about this, here is a simple one where we keep passing adds[i] along as a function argument.
Replace adds[i].address with adds[i] when calling GetLatLng and add a second parameter add to the callback:
GetLatLng(gc, adds[i], function(pos, add) {
...
});
Then modify GetLatLng to use add.address instead of just add and add add to the callback call:
// Get Lat/Lng Location
var GetLatLng = function(gc, add, f) {
var ret = '';
gc.geocode({'address': add.address}, function(res, status) {
if (status == 'OK') {
f(res[0].geometry.location, add);
console.log('Found Here: ' + ret.toString());
}
});
return -1;
};
Then in the callback function, replace all instances of adds[i] with add to use the local variable.
I didn't set up a test but it should theoretically work.
you appear to be overcomplicating things. Any reason why you can't do this?
// Place Markers on the Map
var PlaceMarkers = function (iw, adds, gc) {
var aCt = adds.length;
for(var i = 0; i < aCt; ++i) {
var obj=adds[i];
GetLatLng(gc, obj)
}
};
// Get Lat/Lng Location
var GetLatLng = function(gc, obj) {
var ret = '';
gc.geocode({'address': obj.address}, function(res, status) {
if (status == 'OK') {
var pos=res[0].geometry.location;
var ipop = '<h1>' + obj.title + '</h1>'; // <----- TypeError: adds[i] is undefined
if(!isBlank(obj.url)){
ipop += '' + obj.url + '<br />';
}
ipop += '<div class="map_item_content" id="mi_content">' + obj.content + '</div>';
if(!isBlank(obj.mainphone)){
ipop += '<br /><strong>Phone:</strong> ' + obj.mainphone + '';
}
if(!isBlank(obj.mainemail)){
ipop += '<br /><strong>Email:</strong> ' + obj.mainemail + '';
}
console.log('HEY NOW: ' + pos.toString() + ' - Location Found!');
var mark = new google.maps.Marker({title: obj.title, position: pos, map: map, html: ipop});
google.maps.event.addListener(mark, 'click', function(){
iw.setContent(this.html);
iw.open(map, this);
});
} else {
console.log("geocoder problem!")
}
});
};
for(var i = 0; i < aCt - 1; ++i). You need to add "-1" in you for-loop. The array starts at index 0 and not 1. You also need to be careful with using functions in a for loop. Within javascript a for-loop does not have a scope from itself. Only functions create new scopes.

Google Map:- InvalidValueError: setIcon: not a string; and no url property; and no path property

I am getting this error in google maps.
Error: InvalidValueError: setIcon: not a string; and no url property; and no path property
Earlier it was working fine and i never changed my code.
I have seen a post Google Maps Error: Uncaught InvalidValueError: setIcon: not a string; and no url property; and no path property with same issue and applied the change mentioned in the answer. Earlier it was working and now it also stopped working.
It Seems that google has changed something in their API but not sure what exactly. I found the same issue found by some other users too # https://code.google.com/p/gmaps-api-issues/issues/detail?id=7423
My website link is http://www.advantarealty.net/Search//Condo,Single-Family-Home,Townhome_PropertyType/True_ForMap/ just open in firefox and see the error console.
I have included below js files for map.
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true&libraries=drawing"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.9/src/markerwithlabel.js"></script>
<div id="map-canvas" class="map-view">hello</div>
Below is the complete javascript code which i used.
<script>
var defaultLat = '#Html.Raw(Model != null && Model.Count() > 0 ? Convert.ToDouble(Model[0].Latitude) : 0)';
var defaultLong = '#Html.Raw(Model != null && Model.Count() > 0 ? Convert.ToDouble(Model[0].Longitude) : 0)';
if (defaultLat == 0)
defaultLat = $('#SearchLatitude').val();
if (defaultLong == 0)
defaultLong = $('#SearchLongitude').val();
// var json = JSON.parse('#str');
// Add this for testing only
var json = JSON.parse('[ { "DaysOnAdvanta": "400", "Name": null, "com_address": null, "MLS_ID": "miamimls", "MLS_STATE_ID": "FL", "MLS_LISTING_ID": "A1677437", "mls_office_id": null, "MLS_Office_Name": "EWM Realty International ", "MLS_AGENT_ID": null, "MLS_Agnet_Name": null, "SALE_PRICE": "400000", "Address": "5800 N BAY RD", "city": "Miami Beach", "zip_code": "33140", "remarks": "", "property_type_code": "Residential", "County": null, "Subdivision": "LA GORCE GOLF SUB PB 14-4", "status_code": "Active", "Year_Built": "1929", "acres": "0", "LOT_SQUARE_FOOTAGE": "52881", "BUILDING_SQUARE_FOOTAGE": "12153", "Bedroom_Count": "7", "Full_Baths": "8", "Half_Baths": null, "Fire_place_Number": null, "has_virtual_tour": null, "has_garage": null, "has_firepalce": null, "has_horses": null, "has_pool": null, "has_golf": null, "has_tennis": null, "is_gated": null, "is_waterfront": null, "has_photo": null, "photo_quantity": "25", "photo_url": null, "virtual_tour_url": "http://www.obeo.com/u.aspx?ID=630180", "last_updated": null, "listing_date": null, "garage": null, "last_image_transaction": null, "complex_building": null, "display_address": null, "advertise": null, "IMAGE": "/images/PhotoNotAvailable_Large.gif ", "visit": null, "inforequest": null, "FollwID": 0, "Latitude": "25.83835", "Longitude": "-80.13273", "Special": "", "price_change_direction": "", "location_id": "48153" } ]');
// console.log(json);
var contentString = "<div style='width: 200px; height: 250px;text-align: center;'>" +
"<img src='//image6.sellectrified.com/flex/RX-3/113/RX-3113755-1.jpeg' width='200' alt='No Image' style='max-height: 130px;' />" +
"<table style='width: 100%; border-collapse: collapse;'>" +
"<tr>" +
"<td style='text-align:left;height:20px;'>" +
"$155,000" +
"</td>" +
"<td style='text-align:right;height:20px;'>" +
"2754, Dora Ave" +
"</td>" +
"</tr>" +
"<tr>" +
"<td>" +
"</td>" +
"<td>" +
"<a href='javascript:void(0);'>" +
"<div class='btn btn-primary card-btn'>Details</div>" +
"</a>" +
"</td>" +
"</tr>" +
"</table>" +
"<table style='width: 100%; border-collapse: collapse;border-top:1px solid gray;'>" +
"<tr>" +
"<td style='text-align:center;font-size: 10px;'>" +
"2 BEDS" +
" " +
"1 BATH" +
" " +
"1,235 Sq.ft." +
" " +
"1.3 ACRE" +
"</td>" +
"</tr>" +
"</table>" +
"</div>";
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var m = [];
function initialize() {
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
var myLatlng = new google.maps.LatLng(defaultLat, defaultLong);
var mapOptions = {
center: myLatlng,
zoom: 8
//mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (json.length > 0) {
$(json).each(function (i) {
var latlng = new google.maps.LatLng(json[i].Latitude, json[i].Longitude);
var marker = new MarkerWithLabel({
position: latlng,
draggable: false,
raiseOnDrag: false,
map: map,
labelContent: "$" + (json[i].SALE_PRICE / 1000) + 'k',
labelAnchor: new google.maps.Point(22, 0),
labelClass: "marker", // the CSS class for the label
icon: {},
title: json[i].Address,
id: json[i].MLS_ID + '-' + json[i].MLS_LISTING_ID
});
m.push(marker);
google.maps.event.addListener(marker, 'mouseover', function () {
var contentString = "<div style='width: 200px; text-align: center;'>" +
"<img src='" + json[i].IMAGE + "' width='200' alt='' style='max-height: 130px;' />" +
"<table style='width: 100%;'>" +
"<tr>" +
"<td style='text-align:left;padding: 5px 0;'>" +
"$" + json[i].SALE_PRICE +
"</td>" +
"<td style='text-align:right;padding: 5px 0;'>" +
json[i].Address +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2' style='text-align:right;padding: 5px 0;'>" +
"<a class='orange-btn-small' href='/Home/PropertyDetail/" + json[i].location_id + "/" + json[i].MLS_ID + "/" + json[i].MLS_LISTING_ID + "/" + json[i].Address + "'>Details</a>" +
"</td>" +
"</tr>" +
"</table>" +
"<table style='width: 100%; border-top:1px solid gray;'>" +
"<tr>" +
"<td style='text-align:center;font-size: 10px;'>" +
json[i].Bedroom_Count + " BEDS" +
" " +
json[i].Full_Baths + " BATH" +
" " +
json[i].BUILDING_SQUARE_FOOTAGE + " Sq.ft." +
"</td>" +
"</tr>" +
"</table>" +
"</div>";
infowindow.setContent(contentString);
infowindow.open(map, marker);
//getFocusLeftList(sn);
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
});
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
}
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: null,
//drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
//To add event on circle complete.
google.maps.event.addListener(drawingManager, 'circlecomplete', function (circle) {
var radius = circle.getRadius();
//alert(radius);
});
//To add event on drawing complete.
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
if (event.type == google.maps.drawing.OverlayType.CIRCLE) {
DrawCircleMarker(event.overlay);
var radius = event.overlay.getRadius();
//alert(radius);
}
else if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
var cordinates = event.overlay.getBounds();
// alert(cordinates);
}
else if (event.type == google.maps.drawing.OverlayType.POLYGON) {
var arrayPath = event.overlay.getPath().b;
GetMaxMinLatLng(event.overlay);
$('#Polygon').val(MasterPoly);
changeView($('#map-canvas'), 'map');
}
});
drawingManager.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
var MaxLat = 0;
var MaxLng = 0;
var MinLat = 0;
var MinLng = 0;
var MasterPoly = '';
var Polygon;
function GetMaxMinLatLng(poly) {
var polyPoints = poly.getPath();
var oddNodes = false;
if (Polygon != null)
Polygon.setMap(null);
Polygon = poly;
for (var i = 0; i < polyPoints.getLength() ; i++) {
if (i == 0) {
MaxLat = polyPoints.getAt(i).lat();
MaxLng = polyPoints.getAt(i).lng();
MinLat = polyPoints.getAt(i).lat();
MinLng = polyPoints.getAt(i).lng();
var con = new Contour(polyPoints.j);
var c = con.centroid();
centerLat = c.y;
centerLong = c.x;
centerPoint = new google.maps.LatLng(centerLat, centerLong);
}
if (polyPoints.getAt(i).lat() > MaxLat) {
MaxLat = polyPoints.getAt(i).lat();
$('#SearchLatitude').val(MaxLat);
}
if (polyPoints.getAt(i).lat() < MinLat) {
MinLat = polyPoints.getAt(i).lat();
}
if (polyPoints.getAt(i).lng() > MaxLng) {
MaxLng = polyPoints.getAt(i).lng();
$('#SearchLongitude').val(MaxLng);
}
if (polyPoints.getAt(i).lng() < MinLng) {
MinLng = polyPoints.getAt(i).lng();
}
}
MasterPoly = MinLng + ' ' + MaxLat + ',' + MinLng + ' ' + MinLat + ',' + MaxLng + ' ' + MinLat + ',' + MaxLng + ' ' + MaxLat + ',' + MinLng + ' ' + MaxLat;
}
function Point(x, y) {
this.x = x;
this.y = y;
}
// Contour object
function Contour(points) {
this.pts = points || []; // an array of Point objects defining the contour
}
Contour.prototype.area = function () {
var area = 0;
var pts = this.pts;
var nPts = pts.length - 1;
var j = nPts - 1;
var p1; var p2;
for (var i = 0; i < nPts; j = i++) {
p1 = pts[i]; p2 = pts[j];
area += p1.A * p2.k;
area -= p1.k * p2.A;
}
area /= 2;
return area;
};
Contour.prototype.centroid = function () {
var pts = this.pts;
var nPts = pts.length - 1;
var x = 0; var y = 0;
var f;
var j = nPts - 1;
var p1; var p2;
for (var i = 0; i < nPts; j = i++) {
p1 = pts[i]; p2 = pts[j];
f = p1.A * p2.k - p2.A * p1.k;
x += (p1.A + p2.A) * f;
y += (p1.k + p2.k) * f;
}
f = this.area() * 6;
return new Point(x / f, y / f);
};
$(".SearchProp").hover(function () {
var lat = $(this).attr("lat");
var long = $(this).attr("long");
var sequence = $(this).attr("seq")
google.maps.event.trigger(m[sequence], "mouseover");
var laLatLng = new google.maps.LatLng(lat, long);
});
</script>
Finally I figured out the issue.
Earlier markerwithlabel javascript library, if we want to hide the marker and only want to show the label, we just pass an empty braces to icon parameter like below
var marker = new MarkerWithLabel({
position: latlng,
draggable: false,
raiseOnDrag: false,
map: map,
labelContent: "$" + (json[i].SALE_PRICE / 1000) + 'k',
labelAnchor: new google.maps.Point(22, 0),
labelClass: "marker", // the CSS class for the label
icon: {},
title: json[i].Address,
id: json[i].MLS_ID + '-' + json[i].MLS_LISTING_ID
});
icon: {},
But now it doesn't work, you must have to supply an image icon for that. SO when I supplied a transparent image to icon, it works now.
icon: '/images/transparent-1x1.png',
Also I am now using latest js library for that
http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.10/src/markerwithlabel.js
I happened to fall in the same issue and below is the solution which helped me, I hope this helps you too.
First add this google marker with label script in a JS file- (mine is MarkerWithLabel.js)
https://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/markerwithlabel/src/markerwithlabel.js?r=131
Then add the below mentioned google map JS libraries on the page-
https://maps.googleapis.com/maps/api/js?key=some_key_here&sensor=false
~/Scripts/MarkerWithLabel.js
function showMap() {
var address = $('#corp-add').text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 16
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new MarkerWithLabel({
position: new google.maps.LatLng(latitude, longitude),
draggable: true,
raiseOnDrag: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: { opacity: 0.75 }
});
var iw1 = new google.maps.InfoWindow({
content: "This is a test marker"
});
google.maps.event.addListener(marker, "click", function (e) { iw1.open(map, this); });
}
});
In my code above I am using Google GeoCoder to convert address to Latitudes and Longitudes. You can modify the above code according to your requirements.
You can also follow these links and they might be helpful-
http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.8/docs/examples.html
Let me know if you need more details from me.
Regards,
Manik

Uncaught ReferenceError: google is not defined (Wordpress)

Below is the code I am working with. I'm trying to fix an error with a map not displaying in all browsers.
In dev tools (chrome), I'm getting a Uncaught ReferenceError: google is not defined error.
$(document).ready(function(){
//google map
function loadGoogleMap() {
var mapOptions = {
scrollwheel: false,
zoom: 14,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#map")[0], mapOptions);
var bounds = new google.maps.LatLngBounds();
var count = 0;
$.each(dealers, function(ind,dealer){
var point = new google.maps.LatLng(dealer.lat,dealer.lng)
var marker = new google.maps.Marker({
position: point,
map: map,
title: dealer.post_title,
icon: icons[count]
});
var infowindow = new google.maps.InfoWindow({
content:'<div class="infowindow">'+
'<strong>' + dealer.post_title + '</strong><br/>' +
'<address>' +
dealer.address1 + '<br/>' +
dealer.city + ', ' + dealer.state + '<br/>' +
'</address>' +
dealer.phone + '<br/>' +
(dealer.url != '' ? 'Dealer Website<br/>' : '') +
(dealer.email != '' ? 'Email Dealer<br/>' : '') +
'Get Directions'+
'</div>'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
// add event listener to distributor list
$('#distributors-list li:eq(' + count + ')').click(function(){
infowindow.open(map,marker);
});
bounds.extend(point);
count++;
});
map.fitBounds(bounds);
}
loadGoogleMap();
// reuse fancybox loading icon script
var loadingTimer, loadingFrame = 1;
var locator_animate_loading = function() {
locatorLoading = $('#ajax-loading-overlay');
if (!locatorLoading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$(locatorLoading).css('background-position', '0 ' + (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$('form.distributor-search').submit(function(e){
locatorLoading = $('#ajax-loading-overlay');
locatorLoading.show();
loadingTimer = setInterval(locator_animate_loading, 66);
$('#locator-content').load(site_url + '/graceports/find-a-distributor?ajax=1&address=' + encodeURIComponent($('#address_search').val()) + ' #ajax-contents', function() {
// load updated list of dealers
$('#locator-content').append('<script src="' + site_url + '/js/dealers.php?address=' + encodeURIComponent($('#address_search').val()) + '"></script>');
loadGoogleMap();
locatorLoading.hide();
});
e.preventDefault();
});
navigator.geolocation.getCurrentPosition(function(position){
$.get(site_url + '/cms/wp-content/themes/grace/inc/latlng-to-zip.php?latlng=' + encodeURIComponent(position.coords.latitude + ' ' + position.coords.longitude), function(data){
$('#address_search').val(data);
$('form.distributor-search').trigger('submit');
});
});
});
You need to wait until google has loaded before running your scripts. Put this somewhere in your document:
$(document).ready(function(){
//google map
function loadGoogleMap() {
var mapOptions = {
scrollwheel: false,
zoom: 14,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#map")[0], mapOptions);
var bounds = new google.maps.LatLngBounds();
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
var count = 0;
$.each(dealers, function(ind,dealer){
var point = new google.maps.LatLng(dealer.lat,dealer.lng)
var marker = new google.maps.Marker({
position: point,
map: map,
title: dealer.post_title,
icon: icons[count]
});
var infowindow = new google.maps.InfoWindow({
content:'<div class="infowindow">'+
'<strong>' + dealer.post_title + '</strong><br/>' +
'<address>' +
dealer.address1 + '<br/>' +
dealer.city + ', ' + dealer.state + '<br/>' +
'</address>' +
dealer.phone + '<br/>' +
(dealer.url != '' ? 'Dealer Website<br/>' : '') +
(dealer.email != '' ? 'Email Dealer<br/>' : '') +
'Get Directions'+
'</div>'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
// add event listener to distributor list
$('#distributors-list li:eq(' + count + ')').click(function(){
infowindow.open(map,marker);
});
bounds.extend(point);
count++;
});
map.fitBounds(bounds);
}
loadGoogleMap();
// reuse fancybox loading icon script
var loadingTimer, loadingFrame = 1;
var locator_animate_loading = function() {
locatorLoading = $('#ajax-loading-overlay');
if (!locatorLoading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$(locatorLoading).css('background-position', '0 ' + (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$('form.distributor-search').submit(function(e){
locatorLoading = $('#ajax-loading-overlay');
locatorLoading.show();
loadingTimer = setInterval(locator_animate_loading, 66);
$('#locator-content').load(site_url + '/graceports/find-a-distributor?ajax=1&address=' + encodeURIComponent($('#address_search').val()) + ' #ajax-contents', function() {
// load updated list of dealers
$('#locator-content').append('<script src="' + site_url + '/js/dealers.php?address=' + encodeURIComponent($('#address_search').val()) + '"></script>');
loadGoogleMap();
locatorLoading.hide();
});
e.preventDefault();
});
navigator.geolocation.getCurrentPosition(function(position){
$.get(site_url + '/cms/wp-content/themes/grace/inc/latlng-to-zip.php?latlng=' + encodeURIComponent(position.coords.latitude + ' ' + position.coords.longitude), function(data){
$('#address_search').val(data);
$('form.distributor-search').trigger('submit');
});
});
});

Categories

Resources