I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>
Related
I'm working with Google Maps API for a project and I'm stuck with this Geociding thing for days...
I need to use geocoding to go in reverse and get the lat and lng from a given address, so I need these functions to create the location points.
var glocations = [];
var locations = [];
var infoWindow = new google.maps.InfoWindow({content: ''});
var geocoder;
var map;
function initMap() {
var center = new google.maps.LatLng(40.6976637,-74.1197637);
var mapOptions = {
zoom: 8,
center: center,
mapTypeControl: false,
fullscreenControl: false,
mapTypeId: google.maps.MapTypeId.TRAFFIC,
styles: []
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder = new google.maps.Geocoder();
locations = [
['0', '','Title', codeAddressLat('brooklyn', '0'), codeAddressLng('brooklyn', '0'), 'category-1', 'https://sat.ptvtelecom.net/img/red.png'],//this doesn't work
['1', '', 'Title', 40.6976637,-74.1197637, 'category-2', 'https://sat.ptvtelecom.net/img/green.png']//this works
];
for (i = 0; i < locations.length; i++) {
var url = locations[i][6];
addMarker(locations[i], url);
}
}
function addMarker(marker, url) {
var category = marker[5];
var title = marker[1];
var pos = new google.maps.LatLng(marker[3], marker[4]);
var content = marker[2];
var icon = {
url: url,
scaledSize: new google.maps.Size(32, 32)
};
marker1 = new google.maps.Marker({
title: title,
icon: icon,
position: pos,
category: category,
map: map
});
glocations.push(marker1);
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
infoWindow.setContent(content);
infoWindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(20);
}
})(marker1, content));
}
function codeAddressLat(address, index) {
geocoder.geocode({ 'address': address }, function (results, status) {
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
var lat = latLng.lat;
if (status == 'OK') {
locations[index][3] = lat;//this will change the lat value, but it won't show on map
//return lat;//this will return undefined lat
}
});
}
function codeAddressLng(address, index) {
geocoder.geocode({ 'address': address }, function (results, status) {
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
var lng = latLng.lng;
if (status == 'OK') {
locations[index][4] = lng;//this will change the lng value, but it won't show on map
//return lng;//this will return undefined lng
}
});
}
initMap();
Okay, so I have three outputs here:
If I write down the lat and long values directly, the location will get the float values and the marker show in the map.
If I manipulate the locations array, the location will get float values and the marker won't show in the map.
If the functions return the values, the location will get undefined values and the marker won't show in the map.
You can see what the output looks like in the following screenshot(just url, I can't post images):
sat.ptvtelecom.net/img/result.png
Any help would be so much appreciate.
google map marker not showing in bootstrap modal.
this is my jquery code :
function map_init() {
if(!$('body').data('map')){
var var_mapoptions = {
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: ['roadmap', 'terrain']
}
};
$('body').data('map',new google.maps.Map($('<div id="map"/>')[0],
var_mapoptions));
}
return $('body').data('map');
}
var Lat;
var lon;
$(document).on('click','a[data-map]',function(){
var data=$(this).data('map'),
map=map_init();
var geocoder = new google.maps.Geocoder();
var address = data;
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();
}
Lat = latitude;
lon = longitude;
});
$('#map_modal')
.find('.modal-body')
.append(map.getDiv())
.end()
.find('.modal-title')
.text(data.Name)
.end()
.one('shown.bs.modal',function(){
google.maps.event.trigger(map, "resize");
map.setCenter({lat:Lat,lng:lon});
});
})
.modal('show');
});
it's showing modal , but not showing the map marker. the latitude and longitude values are came from php code( that is from while loop value).
I believe you did not created any Google Maps Javascript API Markers object.
A marker identifies a location on a map. By default, a marker uses a
standard image. Markers can display custom images, in which case they
are usually referred to as "icons."
I would suggest to edit and add this code inside this line:
if ( status == google.maps.GeocoderStatus.OK ) {
//add marker code here
}
code to be added:
var marker = new google.maps.Marker({
positions : new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng() ),
map: map,
title: 'I am a marker :)'
});
And your Marker will appear.
I'm using yii2-google-maps-markers for my webste.
It works fine.
I want to create a search engine, so I want to change the center value of google map after searched result shown.
I could change the center position but all makers removed.
How I can change center by using js with a specified address without removing makers.
My code is below:
view.php
<?php
echo GoogleMaps::widget([
'userLocations' => $locat,
'googleMapsUrlOptions' => [
'key' => Yii::$app->params['GOOGLE_API_KEY'],
],
'googleMapsOptions' => [
],
'wrapperHeight' => '350px',
]);
?>
and current solution
<script type="text/javascript">
// Run function after page loaded
document.addEventListener('DOMContentLoaded', function() {
show_map_theo_address("some where, America");
}, false);
// This is the minimum zoom level that we'll allow
function show_map_theo_address(address) {
var geocoder, vitri;
var minZoomLevel = 15;
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
vitri = results[0].geometry.location;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
}
}
});
}
}
But it does not work.
Please help.
You should separate the logic .. a first part for show the map and all the markers a second part for get the new marker position and set the center
This beacuse you create (recreate) the maps when you use the actual show_map_theo_address function
for avoid the markers deletion you should
create a global var map
<script>
var map;
......
move the creation of the map outside the function show_map_theo_address()
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(YourInitialCenterLat, YourInitialCenterLng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
inside the function show_map_theo_address() use setCenter
// This is the minimum zoom level that we'll allow
function show_map_theo_address(address) {
var geocoder, vitri;
var minZoomLevel = 15;
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
vitri = results[0].geometry.location;
map.setCenter(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
}
}
}
});
}
}
I modified the javascript from https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple to
var geocoder;
var postalArr = [];
postalArr.push(249586);
postalArr.push(266751);
var map;
function initialize(){
var myLatlng = new google.maps.LatLng(1.3667, 103.7500);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
if (postalArr) {
for (var i = 0; i < postalArr.length; i++ ) {
codeAddress(postalArr[i]);
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
function codeAddress(postal) {
geocoder.geocode( { 'postal': postal}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var markerE = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
The script goes within the for loop but doesn't run the codeAddress function.
I'm not sure why.
Two things.
(1) need to define geocoder somewhere, I put it in the initialize
function initialize(){
geocoder = new google.maps.Geocoder();
(2) there's no such thing as a postal property to feed the geocoder. Valid requests are for a latlng or an address as explained here.
So at least you must specify a country. I'm not sure what country 249586 is for, in my demo I used two California zip codes, and added ", United States" to the address.
geocoder.geocode( { 'address': postal + ", United States"},
I'm developing a web page with a Google Maps application and there is something that I'm having trouble with. As it stands, the web page has a functional map (without any layers) and a search bar. I'm new to programming so hopefully there is a quick fix that I'm missing.
When I look up an address, the placemark is is positioned where it is supposed to be. However, when I make a second search with a different address, the placemark of the first search remains visible so that there are two placemarks on the screen. How can I make a new placemark replace the old one?
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
marker.setposition(results [0].geometry.location);
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
One way to achieve what you describe is with a global marker variable. Since the codeAddress function is calling new google.maps.Marker every time it runs, you will get a new marker each time.
Instead, use the setPosition function of the global marker to move it around.
var geocoder;
var map;
// ADDED
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// ADDED
marker = new google.maps.Marker({ map: map });
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
// CHANGED
marker.setPosition(results [0].geometry.location);
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}